]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp
Upgrade to OpenSSH 7.3p1.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaChecking.cpp
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 "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Analysis/Analyses/FormatString.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/TargetBuiltins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/Locale.h"
41 #include "llvm/Support/ConvertUTF.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <limits>
44
45 using namespace clang;
46 using namespace sema;
47
48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49                                                     unsigned ByteNo) const {
50   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51                                Context.getTargetInfo());
52 }
53
54 /// Checks that a call expression's argument count is the desired number.
55 /// This is useful when doing custom type-checking.  Returns true on error.
56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57   unsigned argCount = call->getNumArgs();
58   if (argCount == desiredArgCount) return false;
59
60   if (argCount < desiredArgCount)
61     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62         << 0 /*function call*/ << desiredArgCount << argCount
63         << call->getSourceRange();
64
65   // Highlight all the excess arguments.
66   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67                     call->getArg(argCount - 1)->getLocEnd());
68     
69   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70     << 0 /*function call*/ << desiredArgCount << argCount
71     << call->getArg(1)->getSourceRange();
72 }
73
74 /// Check that the first argument to __builtin_annotation is an integer
75 /// and the second argument is a non-wide string literal.
76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77   if (checkArgCount(S, TheCall, 2))
78     return true;
79
80   // First argument should be an integer.
81   Expr *ValArg = TheCall->getArg(0);
82   QualType Ty = ValArg->getType();
83   if (!Ty->isIntegerType()) {
84     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85       << ValArg->getSourceRange();
86     return true;
87   }
88
89   // Second argument should be a constant string.
90   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92   if (!Literal || !Literal->isAscii()) {
93     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94       << StrArg->getSourceRange();
95     return true;
96   }
97
98   TheCall->setType(Ty);
99   return false;
100 }
101
102 /// Check that the argument to __builtin_addressof is a glvalue, and set the
103 /// result type to the corresponding pointer type.
104 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105   if (checkArgCount(S, TheCall, 1))
106     return true;
107
108   ExprResult Arg(TheCall->getArg(0));
109   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110   if (ResultType.isNull())
111     return true;
112
113   TheCall->setArg(0, Arg.get());
114   TheCall->setType(ResultType);
115   return false;
116 }
117
118 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119   if (checkArgCount(S, TheCall, 3))
120     return true;
121
122   // First two arguments should be integers.
123   for (unsigned I = 0; I < 2; ++I) {
124     Expr *Arg = TheCall->getArg(I);
125     QualType Ty = Arg->getType();
126     if (!Ty->isIntegerType()) {
127       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128           << Ty << Arg->getSourceRange();
129       return true;
130     }
131   }
132
133   // Third argument should be a pointer to a non-const integer.
134   // IRGen correctly handles volatile, restrict, and address spaces, and
135   // the other qualifiers aren't possible.
136   {
137     Expr *Arg = TheCall->getArg(2);
138     QualType Ty = Arg->getType();
139     const auto *PtrTy = Ty->getAs<PointerType>();
140     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141           !PtrTy->getPointeeType().isConstQualified())) {
142       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143           << Ty << Arg->getSourceRange();
144       return true;
145     }
146   }
147
148   return false;
149 }
150
151 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152                                   CallExpr *TheCall, unsigned SizeIdx,
153                                   unsigned DstSizeIdx) {
154   if (TheCall->getNumArgs() <= SizeIdx ||
155       TheCall->getNumArgs() <= DstSizeIdx)
156     return;
157
158   const Expr *SizeArg = TheCall->getArg(SizeIdx);
159   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160
161   llvm::APSInt Size, DstSize;
162
163   // find out if both sizes are known at compile time
164   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166     return;
167
168   if (Size.ule(DstSize))
169     return;
170
171   // confirmed overflow so generate the diagnostic.
172   IdentifierInfo *FnName = FDecl->getIdentifier();
173   SourceLocation SL = TheCall->getLocStart();
174   SourceRange SR = TheCall->getSourceRange();
175
176   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177 }
178
179 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180   if (checkArgCount(S, BuiltinCall, 2))
181     return true;
182
183   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185   Expr *Call = BuiltinCall->getArg(0);
186   Expr *Chain = BuiltinCall->getArg(1);
187
188   if (Call->getStmtClass() != Stmt::CallExprClass) {
189     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190         << Call->getSourceRange();
191     return true;
192   }
193
194   auto CE = cast<CallExpr>(Call);
195   if (CE->getCallee()->getType()->isBlockPointerType()) {
196     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197         << Call->getSourceRange();
198     return true;
199   }
200
201   const Decl *TargetDecl = CE->getCalleeDecl();
202   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203     if (FD->getBuiltinID()) {
204       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205           << Call->getSourceRange();
206       return true;
207     }
208
209   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211         << Call->getSourceRange();
212     return true;
213   }
214
215   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216   if (ChainResult.isInvalid())
217     return true;
218   if (!ChainResult.get()->getType()->isPointerType()) {
219     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220         << Chain->getSourceRange();
221     return true;
222   }
223
224   QualType ReturnTy = CE->getCallReturnType(S.Context);
225   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226   QualType BuiltinTy = S.Context.getFunctionType(
227       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229
230   Builtin =
231       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232
233   BuiltinCall->setType(CE->getType());
234   BuiltinCall->setValueKind(CE->getValueKind());
235   BuiltinCall->setObjectKind(CE->getObjectKind());
236   BuiltinCall->setCallee(Builtin);
237   BuiltinCall->setArg(1, ChainResult.get());
238
239   return false;
240 }
241
242 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243                                      Scope::ScopeFlags NeededScopeFlags,
244                                      unsigned DiagID) {
245   // Scopes aren't available during instantiation. Fortunately, builtin
246   // functions cannot be template args so they cannot be formed through template
247   // instantiation. Therefore checking once during the parse is sufficient.
248   if (!SemaRef.ActiveTemplateInstantiations.empty())
249     return false;
250
251   Scope *S = SemaRef.getCurScope();
252   while (S && !S->isSEHExceptScope())
253     S = S->getParent();
254   if (!S || !(S->getFlags() & NeededScopeFlags)) {
255     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257         << DRE->getDecl()->getIdentifier();
258     return true;
259   }
260
261   return false;
262 }
263
264 static inline bool isBlockPointer(Expr *Arg) {
265   return Arg->getType()->isBlockPointerType();
266 }
267
268 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
269 /// void*, which is a requirement of device side enqueue.
270 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
271   const BlockPointerType *BPT =
272       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
273   ArrayRef<QualType> Params =
274       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
275   unsigned ArgCounter = 0;
276   bool IllegalParams = false;
277   // Iterate through the block parameters until either one is found that is not
278   // a local void*, or the block is valid.
279   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
280        I != E; ++I, ++ArgCounter) {
281     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
282         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
283             LangAS::opencl_local) {
284       // Get the location of the error. If a block literal has been passed
285       // (BlockExpr) then we can point straight to the offending argument,
286       // else we just point to the variable reference.
287       SourceLocation ErrorLoc;
288       if (isa<BlockExpr>(BlockArg)) {
289         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
290         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
291       } else if (isa<DeclRefExpr>(BlockArg)) {
292         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
293       }
294       S.Diag(ErrorLoc,
295              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
296       IllegalParams = true;
297     }
298   }
299
300   return IllegalParams;
301 }
302
303 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
304 /// get_kernel_work_group_size
305 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
306 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
307   if (checkArgCount(S, TheCall, 1))
308     return true;
309
310   Expr *BlockArg = TheCall->getArg(0);
311   if (!isBlockPointer(BlockArg)) {
312     S.Diag(BlockArg->getLocStart(),
313            diag::err_opencl_enqueue_kernel_expected_type) << "block";
314     return true;
315   }
316   return checkOpenCLBlockArgs(S, BlockArg);
317 }
318
319 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
320                                             unsigned Start, unsigned End);
321
322 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
323 /// 'local void*' parameter of passed block.
324 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
325                                            Expr *BlockArg,
326                                            unsigned NumNonVarArgs) {
327   const BlockPointerType *BPT =
328       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
329   unsigned NumBlockParams =
330       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
331   unsigned TotalNumArgs = TheCall->getNumArgs();
332
333   // For each argument passed to the block, a corresponding uint needs to
334   // be passed to describe the size of the local memory.
335   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
336     S.Diag(TheCall->getLocStart(),
337            diag::err_opencl_enqueue_kernel_local_size_args);
338     return true;
339   }
340
341   // Check that the sizes of the local memory are specified by integers.
342   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
343                                          TotalNumArgs - 1);
344 }
345
346 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
347 /// overload formats specified in Table 6.13.17.1.
348 /// int enqueue_kernel(queue_t queue,
349 ///                    kernel_enqueue_flags_t flags,
350 ///                    const ndrange_t ndrange,
351 ///                    void (^block)(void))
352 /// int enqueue_kernel(queue_t queue,
353 ///                    kernel_enqueue_flags_t flags,
354 ///                    const ndrange_t ndrange,
355 ///                    uint num_events_in_wait_list,
356 ///                    clk_event_t *event_wait_list,
357 ///                    clk_event_t *event_ret,
358 ///                    void (^block)(void))
359 /// int enqueue_kernel(queue_t queue,
360 ///                    kernel_enqueue_flags_t flags,
361 ///                    const ndrange_t ndrange,
362 ///                    void (^block)(local void*, ...),
363 ///                    uint size0, ...)
364 /// int enqueue_kernel(queue_t queue,
365 ///                    kernel_enqueue_flags_t flags,
366 ///                    const ndrange_t ndrange,
367 ///                    uint num_events_in_wait_list,
368 ///                    clk_event_t *event_wait_list,
369 ///                    clk_event_t *event_ret,
370 ///                    void (^block)(local void*, ...),
371 ///                    uint size0, ...)
372 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
373   unsigned NumArgs = TheCall->getNumArgs();
374
375   if (NumArgs < 4) {
376     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
377     return true;
378   }
379
380   Expr *Arg0 = TheCall->getArg(0);
381   Expr *Arg1 = TheCall->getArg(1);
382   Expr *Arg2 = TheCall->getArg(2);
383   Expr *Arg3 = TheCall->getArg(3);
384
385   // First argument always needs to be a queue_t type.
386   if (!Arg0->getType()->isQueueT()) {
387     S.Diag(TheCall->getArg(0)->getLocStart(),
388            diag::err_opencl_enqueue_kernel_expected_type)
389         << S.Context.OCLQueueTy;
390     return true;
391   }
392
393   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
394   if (!Arg1->getType()->isIntegerType()) {
395     S.Diag(TheCall->getArg(1)->getLocStart(),
396            diag::err_opencl_enqueue_kernel_expected_type)
397         << "'kernel_enqueue_flags_t' (i.e. uint)";
398     return true;
399   }
400
401   // Third argument is always an ndrange_t type.
402   if (!Arg2->getType()->isNDRangeT()) {
403     S.Diag(TheCall->getArg(2)->getLocStart(),
404            diag::err_opencl_enqueue_kernel_expected_type)
405         << S.Context.OCLNDRangeTy;
406     return true;
407   }
408
409   // With four arguments, there is only one form that the function could be
410   // called in: no events and no variable arguments.
411   if (NumArgs == 4) {
412     // check that the last argument is the right block type.
413     if (!isBlockPointer(Arg3)) {
414       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
415           << "block";
416       return true;
417     }
418     // we have a block type, check the prototype
419     const BlockPointerType *BPT =
420         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
421     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
422       S.Diag(Arg3->getLocStart(),
423              diag::err_opencl_enqueue_kernel_blocks_no_args);
424       return true;
425     }
426     return false;
427   }
428   // we can have block + varargs.
429   if (isBlockPointer(Arg3))
430     return (checkOpenCLBlockArgs(S, Arg3) ||
431             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
432   // last two cases with either exactly 7 args or 7 args and varargs.
433   if (NumArgs >= 7) {
434     // check common block argument.
435     Expr *Arg6 = TheCall->getArg(6);
436     if (!isBlockPointer(Arg6)) {
437       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
438           << "block";
439       return true;
440     }
441     if (checkOpenCLBlockArgs(S, Arg6))
442       return true;
443
444     // Forth argument has to be any integer type.
445     if (!Arg3->getType()->isIntegerType()) {
446       S.Diag(TheCall->getArg(3)->getLocStart(),
447              diag::err_opencl_enqueue_kernel_expected_type)
448           << "integer";
449       return true;
450     }
451     // check remaining common arguments.
452     Expr *Arg4 = TheCall->getArg(4);
453     Expr *Arg5 = TheCall->getArg(5);
454
455     // Fith argument is always passed as pointers to clk_event_t.
456     if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
457       S.Diag(TheCall->getArg(4)->getLocStart(),
458              diag::err_opencl_enqueue_kernel_expected_type)
459           << S.Context.getPointerType(S.Context.OCLClkEventTy);
460       return true;
461     }
462
463     // Sixth argument is always passed as pointers to clk_event_t.
464     if (!(Arg5->getType()->isPointerType() &&
465           Arg5->getType()->getPointeeType()->isClkEventT())) {
466       S.Diag(TheCall->getArg(5)->getLocStart(),
467              diag::err_opencl_enqueue_kernel_expected_type)
468           << S.Context.getPointerType(S.Context.OCLClkEventTy);
469       return true;
470     }
471
472     if (NumArgs == 7)
473       return false;
474
475     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
476   }
477
478   // None of the specific case has been detected, give generic error
479   S.Diag(TheCall->getLocStart(),
480          diag::err_opencl_enqueue_kernel_incorrect_args);
481   return true;
482 }
483
484 /// Returns OpenCL access qual.
485 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
486     return D->getAttr<OpenCLAccessAttr>();
487 }
488
489 /// Returns true if pipe element type is different from the pointer.
490 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
491   const Expr *Arg0 = Call->getArg(0);
492   // First argument type should always be pipe.
493   if (!Arg0->getType()->isPipeType()) {
494     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
495         << Call->getDirectCallee() << Arg0->getSourceRange();
496     return true;
497   }
498   OpenCLAccessAttr *AccessQual =
499       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
500   // Validates the access qualifier is compatible with the call.
501   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
502   // read_only and write_only, and assumed to be read_only if no qualifier is
503   // specified.
504   switch (Call->getDirectCallee()->getBuiltinID()) {
505   case Builtin::BIread_pipe:
506   case Builtin::BIreserve_read_pipe:
507   case Builtin::BIcommit_read_pipe:
508   case Builtin::BIwork_group_reserve_read_pipe:
509   case Builtin::BIsub_group_reserve_read_pipe:
510   case Builtin::BIwork_group_commit_read_pipe:
511   case Builtin::BIsub_group_commit_read_pipe:
512     if (!(!AccessQual || AccessQual->isReadOnly())) {
513       S.Diag(Arg0->getLocStart(),
514              diag::err_opencl_builtin_pipe_invalid_access_modifier)
515           << "read_only" << Arg0->getSourceRange();
516       return true;
517     }
518     break;
519   case Builtin::BIwrite_pipe:
520   case Builtin::BIreserve_write_pipe:
521   case Builtin::BIcommit_write_pipe:
522   case Builtin::BIwork_group_reserve_write_pipe:
523   case Builtin::BIsub_group_reserve_write_pipe:
524   case Builtin::BIwork_group_commit_write_pipe:
525   case Builtin::BIsub_group_commit_write_pipe:
526     if (!(AccessQual && AccessQual->isWriteOnly())) {
527       S.Diag(Arg0->getLocStart(),
528              diag::err_opencl_builtin_pipe_invalid_access_modifier)
529           << "write_only" << Arg0->getSourceRange();
530       return true;
531     }
532     break;
533   default:
534     break;
535   }
536   return false;
537 }
538
539 /// Returns true if pipe element type is different from the pointer.
540 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
541   const Expr *Arg0 = Call->getArg(0);
542   const Expr *ArgIdx = Call->getArg(Idx);
543   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
544   const QualType EltTy = PipeTy->getElementType();
545   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
546   // The Idx argument should be a pointer and the type of the pointer and
547   // the type of pipe element should also be the same.
548   if (!ArgTy ||
549       !S.Context.hasSameType(
550           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
551     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
552         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
553         << ArgIdx->getType() << ArgIdx->getSourceRange();
554     return true;
555   }
556   return false;
557 }
558
559 // \brief Performs semantic analysis for the read/write_pipe call.
560 // \param S Reference to the semantic analyzer.
561 // \param Call A pointer to the builtin call.
562 // \return True if a semantic error has been found, false otherwise.
563 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
564   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
565   // functions have two forms.
566   switch (Call->getNumArgs()) {
567   case 2: {
568     if (checkOpenCLPipeArg(S, Call))
569       return true;
570     // The call with 2 arguments should be
571     // read/write_pipe(pipe T, T*).
572     // Check packet type T.
573     if (checkOpenCLPipePacketType(S, Call, 1))
574       return true;
575   } break;
576
577   case 4: {
578     if (checkOpenCLPipeArg(S, Call))
579       return true;
580     // The call with 4 arguments should be
581     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
582     // Check reserve_id_t.
583     if (!Call->getArg(1)->getType()->isReserveIDT()) {
584       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
585           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
586           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
587       return true;
588     }
589
590     // Check the index.
591     const Expr *Arg2 = Call->getArg(2);
592     if (!Arg2->getType()->isIntegerType() &&
593         !Arg2->getType()->isUnsignedIntegerType()) {
594       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
595           << Call->getDirectCallee() << S.Context.UnsignedIntTy
596           << Arg2->getType() << Arg2->getSourceRange();
597       return true;
598     }
599
600     // Check packet type T.
601     if (checkOpenCLPipePacketType(S, Call, 3))
602       return true;
603   } break;
604   default:
605     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
606         << Call->getDirectCallee() << Call->getSourceRange();
607     return true;
608   }
609
610   return false;
611 }
612
613 // \brief Performs a semantic analysis on the {work_group_/sub_group_
614 //        /_}reserve_{read/write}_pipe
615 // \param S Reference to the semantic analyzer.
616 // \param Call The call to the builtin function to be analyzed.
617 // \return True if a semantic error was found, false otherwise.
618 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
619   if (checkArgCount(S, Call, 2))
620     return true;
621
622   if (checkOpenCLPipeArg(S, Call))
623     return true;
624
625   // Check the reserve size.
626   if (!Call->getArg(1)->getType()->isIntegerType() &&
627       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
628     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
629         << Call->getDirectCallee() << S.Context.UnsignedIntTy
630         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
631     return true;
632   }
633
634   return false;
635 }
636
637 // \brief Performs a semantic analysis on {work_group_/sub_group_
638 //        /_}commit_{read/write}_pipe
639 // \param S Reference to the semantic analyzer.
640 // \param Call The call to the builtin function to be analyzed.
641 // \return True if a semantic error was found, false otherwise.
642 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
643   if (checkArgCount(S, Call, 2))
644     return true;
645
646   if (checkOpenCLPipeArg(S, Call))
647     return true;
648
649   // Check reserve_id_t.
650   if (!Call->getArg(1)->getType()->isReserveIDT()) {
651     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
652         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
653         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
654     return true;
655   }
656
657   return false;
658 }
659
660 // \brief Performs a semantic analysis on the call to built-in Pipe
661 //        Query Functions.
662 // \param S Reference to the semantic analyzer.
663 // \param Call The call to the builtin function to be analyzed.
664 // \return True if a semantic error was found, false otherwise.
665 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
666   if (checkArgCount(S, Call, 1))
667     return true;
668
669   if (!Call->getArg(0)->getType()->isPipeType()) {
670     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
671         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
672     return true;
673   }
674
675   return false;
676 }
677 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
678 // \brief Performs semantic analysis for the to_global/local/private call.
679 // \param S Reference to the semantic analyzer.
680 // \param BuiltinID ID of the builtin function.
681 // \param Call A pointer to the builtin call.
682 // \return True if a semantic error has been found, false otherwise.
683 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
684                                     CallExpr *Call) {
685   if (Call->getNumArgs() != 1) {
686     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
687         << Call->getDirectCallee() << Call->getSourceRange();
688     return true;
689   }
690
691   auto RT = Call->getArg(0)->getType();
692   if (!RT->isPointerType() || RT->getPointeeType()
693       .getAddressSpace() == LangAS::opencl_constant) {
694     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
695         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
696     return true;
697   }
698
699   RT = RT->getPointeeType();
700   auto Qual = RT.getQualifiers();
701   switch (BuiltinID) {
702   case Builtin::BIto_global:
703     Qual.setAddressSpace(LangAS::opencl_global);
704     break;
705   case Builtin::BIto_local:
706     Qual.setAddressSpace(LangAS::opencl_local);
707     break;
708   default:
709     Qual.removeAddressSpace();
710   }
711   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
712       RT.getUnqualifiedType(), Qual)));
713
714   return false;
715 }
716
717 ExprResult
718 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
719                                CallExpr *TheCall) {
720   ExprResult TheCallResult(TheCall);
721
722   // Find out if any arguments are required to be integer constant expressions.
723   unsigned ICEArguments = 0;
724   ASTContext::GetBuiltinTypeError Error;
725   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
726   if (Error != ASTContext::GE_None)
727     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
728   
729   // If any arguments are required to be ICE's, check and diagnose.
730   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
731     // Skip arguments not required to be ICE's.
732     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
733     
734     llvm::APSInt Result;
735     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
736       return true;
737     ICEArguments &= ~(1 << ArgNo);
738   }
739   
740   switch (BuiltinID) {
741   case Builtin::BI__builtin___CFStringMakeConstantString:
742     assert(TheCall->getNumArgs() == 1 &&
743            "Wrong # arguments to builtin CFStringMakeConstantString");
744     if (CheckObjCString(TheCall->getArg(0)))
745       return ExprError();
746     break;
747   case Builtin::BI__builtin_stdarg_start:
748   case Builtin::BI__builtin_va_start:
749     if (SemaBuiltinVAStart(TheCall))
750       return ExprError();
751     break;
752   case Builtin::BI__va_start: {
753     switch (Context.getTargetInfo().getTriple().getArch()) {
754     case llvm::Triple::arm:
755     case llvm::Triple::thumb:
756       if (SemaBuiltinVAStartARM(TheCall))
757         return ExprError();
758       break;
759     default:
760       if (SemaBuiltinVAStart(TheCall))
761         return ExprError();
762       break;
763     }
764     break;
765   }
766   case Builtin::BI__builtin_isgreater:
767   case Builtin::BI__builtin_isgreaterequal:
768   case Builtin::BI__builtin_isless:
769   case Builtin::BI__builtin_islessequal:
770   case Builtin::BI__builtin_islessgreater:
771   case Builtin::BI__builtin_isunordered:
772     if (SemaBuiltinUnorderedCompare(TheCall))
773       return ExprError();
774     break;
775   case Builtin::BI__builtin_fpclassify:
776     if (SemaBuiltinFPClassification(TheCall, 6))
777       return ExprError();
778     break;
779   case Builtin::BI__builtin_isfinite:
780   case Builtin::BI__builtin_isinf:
781   case Builtin::BI__builtin_isinf_sign:
782   case Builtin::BI__builtin_isnan:
783   case Builtin::BI__builtin_isnormal:
784     if (SemaBuiltinFPClassification(TheCall, 1))
785       return ExprError();
786     break;
787   case Builtin::BI__builtin_shufflevector:
788     return SemaBuiltinShuffleVector(TheCall);
789     // TheCall will be freed by the smart pointer here, but that's fine, since
790     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
791   case Builtin::BI__builtin_prefetch:
792     if (SemaBuiltinPrefetch(TheCall))
793       return ExprError();
794     break;
795   case Builtin::BI__assume:
796   case Builtin::BI__builtin_assume:
797     if (SemaBuiltinAssume(TheCall))
798       return ExprError();
799     break;
800   case Builtin::BI__builtin_assume_aligned:
801     if (SemaBuiltinAssumeAligned(TheCall))
802       return ExprError();
803     break;
804   case Builtin::BI__builtin_object_size:
805     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
806       return ExprError();
807     break;
808   case Builtin::BI__builtin_longjmp:
809     if (SemaBuiltinLongjmp(TheCall))
810       return ExprError();
811     break;
812   case Builtin::BI__builtin_setjmp:
813     if (SemaBuiltinSetjmp(TheCall))
814       return ExprError();
815     break;
816   case Builtin::BI_setjmp:
817   case Builtin::BI_setjmpex:
818     if (checkArgCount(*this, TheCall, 1))
819       return true;
820     break;
821
822   case Builtin::BI__builtin_classify_type:
823     if (checkArgCount(*this, TheCall, 1)) return true;
824     TheCall->setType(Context.IntTy);
825     break;
826   case Builtin::BI__builtin_constant_p:
827     if (checkArgCount(*this, TheCall, 1)) return true;
828     TheCall->setType(Context.IntTy);
829     break;
830   case Builtin::BI__sync_fetch_and_add:
831   case Builtin::BI__sync_fetch_and_add_1:
832   case Builtin::BI__sync_fetch_and_add_2:
833   case Builtin::BI__sync_fetch_and_add_4:
834   case Builtin::BI__sync_fetch_and_add_8:
835   case Builtin::BI__sync_fetch_and_add_16:
836   case Builtin::BI__sync_fetch_and_sub:
837   case Builtin::BI__sync_fetch_and_sub_1:
838   case Builtin::BI__sync_fetch_and_sub_2:
839   case Builtin::BI__sync_fetch_and_sub_4:
840   case Builtin::BI__sync_fetch_and_sub_8:
841   case Builtin::BI__sync_fetch_and_sub_16:
842   case Builtin::BI__sync_fetch_and_or:
843   case Builtin::BI__sync_fetch_and_or_1:
844   case Builtin::BI__sync_fetch_and_or_2:
845   case Builtin::BI__sync_fetch_and_or_4:
846   case Builtin::BI__sync_fetch_and_or_8:
847   case Builtin::BI__sync_fetch_and_or_16:
848   case Builtin::BI__sync_fetch_and_and:
849   case Builtin::BI__sync_fetch_and_and_1:
850   case Builtin::BI__sync_fetch_and_and_2:
851   case Builtin::BI__sync_fetch_and_and_4:
852   case Builtin::BI__sync_fetch_and_and_8:
853   case Builtin::BI__sync_fetch_and_and_16:
854   case Builtin::BI__sync_fetch_and_xor:
855   case Builtin::BI__sync_fetch_and_xor_1:
856   case Builtin::BI__sync_fetch_and_xor_2:
857   case Builtin::BI__sync_fetch_and_xor_4:
858   case Builtin::BI__sync_fetch_and_xor_8:
859   case Builtin::BI__sync_fetch_and_xor_16:
860   case Builtin::BI__sync_fetch_and_nand:
861   case Builtin::BI__sync_fetch_and_nand_1:
862   case Builtin::BI__sync_fetch_and_nand_2:
863   case Builtin::BI__sync_fetch_and_nand_4:
864   case Builtin::BI__sync_fetch_and_nand_8:
865   case Builtin::BI__sync_fetch_and_nand_16:
866   case Builtin::BI__sync_add_and_fetch:
867   case Builtin::BI__sync_add_and_fetch_1:
868   case Builtin::BI__sync_add_and_fetch_2:
869   case Builtin::BI__sync_add_and_fetch_4:
870   case Builtin::BI__sync_add_and_fetch_8:
871   case Builtin::BI__sync_add_and_fetch_16:
872   case Builtin::BI__sync_sub_and_fetch:
873   case Builtin::BI__sync_sub_and_fetch_1:
874   case Builtin::BI__sync_sub_and_fetch_2:
875   case Builtin::BI__sync_sub_and_fetch_4:
876   case Builtin::BI__sync_sub_and_fetch_8:
877   case Builtin::BI__sync_sub_and_fetch_16:
878   case Builtin::BI__sync_and_and_fetch:
879   case Builtin::BI__sync_and_and_fetch_1:
880   case Builtin::BI__sync_and_and_fetch_2:
881   case Builtin::BI__sync_and_and_fetch_4:
882   case Builtin::BI__sync_and_and_fetch_8:
883   case Builtin::BI__sync_and_and_fetch_16:
884   case Builtin::BI__sync_or_and_fetch:
885   case Builtin::BI__sync_or_and_fetch_1:
886   case Builtin::BI__sync_or_and_fetch_2:
887   case Builtin::BI__sync_or_and_fetch_4:
888   case Builtin::BI__sync_or_and_fetch_8:
889   case Builtin::BI__sync_or_and_fetch_16:
890   case Builtin::BI__sync_xor_and_fetch:
891   case Builtin::BI__sync_xor_and_fetch_1:
892   case Builtin::BI__sync_xor_and_fetch_2:
893   case Builtin::BI__sync_xor_and_fetch_4:
894   case Builtin::BI__sync_xor_and_fetch_8:
895   case Builtin::BI__sync_xor_and_fetch_16:
896   case Builtin::BI__sync_nand_and_fetch:
897   case Builtin::BI__sync_nand_and_fetch_1:
898   case Builtin::BI__sync_nand_and_fetch_2:
899   case Builtin::BI__sync_nand_and_fetch_4:
900   case Builtin::BI__sync_nand_and_fetch_8:
901   case Builtin::BI__sync_nand_and_fetch_16:
902   case Builtin::BI__sync_val_compare_and_swap:
903   case Builtin::BI__sync_val_compare_and_swap_1:
904   case Builtin::BI__sync_val_compare_and_swap_2:
905   case Builtin::BI__sync_val_compare_and_swap_4:
906   case Builtin::BI__sync_val_compare_and_swap_8:
907   case Builtin::BI__sync_val_compare_and_swap_16:
908   case Builtin::BI__sync_bool_compare_and_swap:
909   case Builtin::BI__sync_bool_compare_and_swap_1:
910   case Builtin::BI__sync_bool_compare_and_swap_2:
911   case Builtin::BI__sync_bool_compare_and_swap_4:
912   case Builtin::BI__sync_bool_compare_and_swap_8:
913   case Builtin::BI__sync_bool_compare_and_swap_16:
914   case Builtin::BI__sync_lock_test_and_set:
915   case Builtin::BI__sync_lock_test_and_set_1:
916   case Builtin::BI__sync_lock_test_and_set_2:
917   case Builtin::BI__sync_lock_test_and_set_4:
918   case Builtin::BI__sync_lock_test_and_set_8:
919   case Builtin::BI__sync_lock_test_and_set_16:
920   case Builtin::BI__sync_lock_release:
921   case Builtin::BI__sync_lock_release_1:
922   case Builtin::BI__sync_lock_release_2:
923   case Builtin::BI__sync_lock_release_4:
924   case Builtin::BI__sync_lock_release_8:
925   case Builtin::BI__sync_lock_release_16:
926   case Builtin::BI__sync_swap:
927   case Builtin::BI__sync_swap_1:
928   case Builtin::BI__sync_swap_2:
929   case Builtin::BI__sync_swap_4:
930   case Builtin::BI__sync_swap_8:
931   case Builtin::BI__sync_swap_16:
932     return SemaBuiltinAtomicOverloaded(TheCallResult);
933   case Builtin::BI__builtin_nontemporal_load:
934   case Builtin::BI__builtin_nontemporal_store:
935     return SemaBuiltinNontemporalOverloaded(TheCallResult);
936 #define BUILTIN(ID, TYPE, ATTRS)
937 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
938   case Builtin::BI##ID: \
939     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
940 #include "clang/Basic/Builtins.def"
941   case Builtin::BI__builtin_annotation:
942     if (SemaBuiltinAnnotation(*this, TheCall))
943       return ExprError();
944     break;
945   case Builtin::BI__builtin_addressof:
946     if (SemaBuiltinAddressof(*this, TheCall))
947       return ExprError();
948     break;
949   case Builtin::BI__builtin_add_overflow:
950   case Builtin::BI__builtin_sub_overflow:
951   case Builtin::BI__builtin_mul_overflow:
952     if (SemaBuiltinOverflow(*this, TheCall))
953       return ExprError();
954     break;
955   case Builtin::BI__builtin_operator_new:
956   case Builtin::BI__builtin_operator_delete:
957     if (!getLangOpts().CPlusPlus) {
958       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
959         << (BuiltinID == Builtin::BI__builtin_operator_new
960                 ? "__builtin_operator_new"
961                 : "__builtin_operator_delete")
962         << "C++";
963       return ExprError();
964     }
965     // CodeGen assumes it can find the global new and delete to call,
966     // so ensure that they are declared.
967     DeclareGlobalNewDelete();
968     break;
969
970   // check secure string manipulation functions where overflows
971   // are detectable at compile time
972   case Builtin::BI__builtin___memcpy_chk:
973   case Builtin::BI__builtin___memmove_chk:
974   case Builtin::BI__builtin___memset_chk:
975   case Builtin::BI__builtin___strlcat_chk:
976   case Builtin::BI__builtin___strlcpy_chk:
977   case Builtin::BI__builtin___strncat_chk:
978   case Builtin::BI__builtin___strncpy_chk:
979   case Builtin::BI__builtin___stpncpy_chk:
980     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
981     break;
982   case Builtin::BI__builtin___memccpy_chk:
983     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
984     break;
985   case Builtin::BI__builtin___snprintf_chk:
986   case Builtin::BI__builtin___vsnprintf_chk:
987     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
988     break;
989   case Builtin::BI__builtin_call_with_static_chain:
990     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
991       return ExprError();
992     break;
993   case Builtin::BI__exception_code:
994   case Builtin::BI_exception_code:
995     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
996                                  diag::err_seh___except_block))
997       return ExprError();
998     break;
999   case Builtin::BI__exception_info:
1000   case Builtin::BI_exception_info:
1001     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1002                                  diag::err_seh___except_filter))
1003       return ExprError();
1004     break;
1005   case Builtin::BI__GetExceptionInfo:
1006     if (checkArgCount(*this, TheCall, 1))
1007       return ExprError();
1008
1009     if (CheckCXXThrowOperand(
1010             TheCall->getLocStart(),
1011             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1012             TheCall))
1013       return ExprError();
1014
1015     TheCall->setType(Context.VoidPtrTy);
1016     break;
1017   // OpenCL v2.0, s6.13.16 - Pipe functions
1018   case Builtin::BIread_pipe:
1019   case Builtin::BIwrite_pipe:
1020     // Since those two functions are declared with var args, we need a semantic
1021     // check for the argument.
1022     if (SemaBuiltinRWPipe(*this, TheCall))
1023       return ExprError();
1024     break;
1025   case Builtin::BIreserve_read_pipe:
1026   case Builtin::BIreserve_write_pipe:
1027   case Builtin::BIwork_group_reserve_read_pipe:
1028   case Builtin::BIwork_group_reserve_write_pipe:
1029   case Builtin::BIsub_group_reserve_read_pipe:
1030   case Builtin::BIsub_group_reserve_write_pipe:
1031     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032       return ExprError();
1033     // Since return type of reserve_read/write_pipe built-in function is
1034     // reserve_id_t, which is not defined in the builtin def file , we used int
1035     // as return type and need to override the return type of these functions.
1036     TheCall->setType(Context.OCLReserveIDTy);
1037     break;
1038   case Builtin::BIcommit_read_pipe:
1039   case Builtin::BIcommit_write_pipe:
1040   case Builtin::BIwork_group_commit_read_pipe:
1041   case Builtin::BIwork_group_commit_write_pipe:
1042   case Builtin::BIsub_group_commit_read_pipe:
1043   case Builtin::BIsub_group_commit_write_pipe:
1044     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045       return ExprError();
1046     break;
1047   case Builtin::BIget_pipe_num_packets:
1048   case Builtin::BIget_pipe_max_packets:
1049     if (SemaBuiltinPipePackets(*this, TheCall))
1050       return ExprError();
1051     break;
1052   case Builtin::BIto_global:
1053   case Builtin::BIto_local:
1054   case Builtin::BIto_private:
1055     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1056       return ExprError();
1057     break;
1058   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1059   case Builtin::BIenqueue_kernel:
1060     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1061       return ExprError();
1062     break;
1063   case Builtin::BIget_kernel_work_group_size:
1064   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1065     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1066       return ExprError();
1067   }
1068
1069   // Since the target specific builtins for each arch overlap, only check those
1070   // of the arch we are compiling for.
1071   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1072     switch (Context.getTargetInfo().getTriple().getArch()) {
1073       case llvm::Triple::arm:
1074       case llvm::Triple::armeb:
1075       case llvm::Triple::thumb:
1076       case llvm::Triple::thumbeb:
1077         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1078           return ExprError();
1079         break;
1080       case llvm::Triple::aarch64:
1081       case llvm::Triple::aarch64_be:
1082         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1083           return ExprError();
1084         break;
1085       case llvm::Triple::mips:
1086       case llvm::Triple::mipsel:
1087       case llvm::Triple::mips64:
1088       case llvm::Triple::mips64el:
1089         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1090           return ExprError();
1091         break;
1092       case llvm::Triple::systemz:
1093         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1094           return ExprError();
1095         break;
1096       case llvm::Triple::x86:
1097       case llvm::Triple::x86_64:
1098         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1099           return ExprError();
1100         break;
1101       case llvm::Triple::ppc:
1102       case llvm::Triple::ppc64:
1103       case llvm::Triple::ppc64le:
1104         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1105           return ExprError();
1106         break;
1107       default:
1108         break;
1109     }
1110   }
1111
1112   return TheCallResult;
1113 }
1114
1115 // Get the valid immediate range for the specified NEON type code.
1116 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1117   NeonTypeFlags Type(t);
1118   int IsQuad = ForceQuad ? true : Type.isQuad();
1119   switch (Type.getEltType()) {
1120   case NeonTypeFlags::Int8:
1121   case NeonTypeFlags::Poly8:
1122     return shift ? 7 : (8 << IsQuad) - 1;
1123   case NeonTypeFlags::Int16:
1124   case NeonTypeFlags::Poly16:
1125     return shift ? 15 : (4 << IsQuad) - 1;
1126   case NeonTypeFlags::Int32:
1127     return shift ? 31 : (2 << IsQuad) - 1;
1128   case NeonTypeFlags::Int64:
1129   case NeonTypeFlags::Poly64:
1130     return shift ? 63 : (1 << IsQuad) - 1;
1131   case NeonTypeFlags::Poly128:
1132     return shift ? 127 : (1 << IsQuad) - 1;
1133   case NeonTypeFlags::Float16:
1134     assert(!shift && "cannot shift float types!");
1135     return (4 << IsQuad) - 1;
1136   case NeonTypeFlags::Float32:
1137     assert(!shift && "cannot shift float types!");
1138     return (2 << IsQuad) - 1;
1139   case NeonTypeFlags::Float64:
1140     assert(!shift && "cannot shift float types!");
1141     return (1 << IsQuad) - 1;
1142   }
1143   llvm_unreachable("Invalid NeonTypeFlag!");
1144 }
1145
1146 /// getNeonEltType - Return the QualType corresponding to the elements of
1147 /// the vector type specified by the NeonTypeFlags.  This is used to check
1148 /// the pointer arguments for Neon load/store intrinsics.
1149 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1150                                bool IsPolyUnsigned, bool IsInt64Long) {
1151   switch (Flags.getEltType()) {
1152   case NeonTypeFlags::Int8:
1153     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1154   case NeonTypeFlags::Int16:
1155     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1156   case NeonTypeFlags::Int32:
1157     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1158   case NeonTypeFlags::Int64:
1159     if (IsInt64Long)
1160       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1161     else
1162       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1163                                 : Context.LongLongTy;
1164   case NeonTypeFlags::Poly8:
1165     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1166   case NeonTypeFlags::Poly16:
1167     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1168   case NeonTypeFlags::Poly64:
1169     if (IsInt64Long)
1170       return Context.UnsignedLongTy;
1171     else
1172       return Context.UnsignedLongLongTy;
1173   case NeonTypeFlags::Poly128:
1174     break;
1175   case NeonTypeFlags::Float16:
1176     return Context.HalfTy;
1177   case NeonTypeFlags::Float32:
1178     return Context.FloatTy;
1179   case NeonTypeFlags::Float64:
1180     return Context.DoubleTy;
1181   }
1182   llvm_unreachable("Invalid NeonTypeFlag!");
1183 }
1184
1185 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1186   llvm::APSInt Result;
1187   uint64_t mask = 0;
1188   unsigned TV = 0;
1189   int PtrArgNum = -1;
1190   bool HasConstPtr = false;
1191   switch (BuiltinID) {
1192 #define GET_NEON_OVERLOAD_CHECK
1193 #include "clang/Basic/arm_neon.inc"
1194 #undef GET_NEON_OVERLOAD_CHECK
1195   }
1196
1197   // For NEON intrinsics which are overloaded on vector element type, validate
1198   // the immediate which specifies which variant to emit.
1199   unsigned ImmArg = TheCall->getNumArgs()-1;
1200   if (mask) {
1201     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1202       return true;
1203
1204     TV = Result.getLimitedValue(64);
1205     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1206       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1207         << TheCall->getArg(ImmArg)->getSourceRange();
1208   }
1209
1210   if (PtrArgNum >= 0) {
1211     // Check that pointer arguments have the specified type.
1212     Expr *Arg = TheCall->getArg(PtrArgNum);
1213     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1214       Arg = ICE->getSubExpr();
1215     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1216     QualType RHSTy = RHS.get()->getType();
1217
1218     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1219     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1220     bool IsInt64Long =
1221         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1222     QualType EltTy =
1223         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1224     if (HasConstPtr)
1225       EltTy = EltTy.withConst();
1226     QualType LHSTy = Context.getPointerType(EltTy);
1227     AssignConvertType ConvTy;
1228     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1229     if (RHS.isInvalid())
1230       return true;
1231     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1232                                  RHS.get(), AA_Assigning))
1233       return true;
1234   }
1235
1236   // For NEON intrinsics which take an immediate value as part of the
1237   // instruction, range check them here.
1238   unsigned i = 0, l = 0, u = 0;
1239   switch (BuiltinID) {
1240   default:
1241     return false;
1242 #define GET_NEON_IMMEDIATE_CHECK
1243 #include "clang/Basic/arm_neon.inc"
1244 #undef GET_NEON_IMMEDIATE_CHECK
1245   }
1246
1247   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1248 }
1249
1250 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1251                                         unsigned MaxWidth) {
1252   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1253           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1254           BuiltinID == ARM::BI__builtin_arm_strex ||
1255           BuiltinID == ARM::BI__builtin_arm_stlex ||
1256           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1257           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1258           BuiltinID == AArch64::BI__builtin_arm_strex ||
1259           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1260          "unexpected ARM builtin");
1261   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1262                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1263                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1264                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1265
1266   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1267
1268   // Ensure that we have the proper number of arguments.
1269   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1270     return true;
1271
1272   // Inspect the pointer argument of the atomic builtin.  This should always be
1273   // a pointer type, whose element is an integral scalar or pointer type.
1274   // Because it is a pointer type, we don't have to worry about any implicit
1275   // casts here.
1276   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1277   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1278   if (PointerArgRes.isInvalid())
1279     return true;
1280   PointerArg = PointerArgRes.get();
1281
1282   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1283   if (!pointerType) {
1284     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1285       << PointerArg->getType() << PointerArg->getSourceRange();
1286     return true;
1287   }
1288
1289   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1290   // task is to insert the appropriate casts into the AST. First work out just
1291   // what the appropriate type is.
1292   QualType ValType = pointerType->getPointeeType();
1293   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1294   if (IsLdrex)
1295     AddrType.addConst();
1296
1297   // Issue a warning if the cast is dodgy.
1298   CastKind CastNeeded = CK_NoOp;
1299   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1300     CastNeeded = CK_BitCast;
1301     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1302       << PointerArg->getType()
1303       << Context.getPointerType(AddrType)
1304       << AA_Passing << PointerArg->getSourceRange();
1305   }
1306
1307   // Finally, do the cast and replace the argument with the corrected version.
1308   AddrType = Context.getPointerType(AddrType);
1309   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1310   if (PointerArgRes.isInvalid())
1311     return true;
1312   PointerArg = PointerArgRes.get();
1313
1314   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1315
1316   // In general, we allow ints, floats and pointers to be loaded and stored.
1317   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1318       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1319     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1320       << PointerArg->getType() << PointerArg->getSourceRange();
1321     return true;
1322   }
1323
1324   // But ARM doesn't have instructions to deal with 128-bit versions.
1325   if (Context.getTypeSize(ValType) > MaxWidth) {
1326     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1327     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1328       << PointerArg->getType() << PointerArg->getSourceRange();
1329     return true;
1330   }
1331
1332   switch (ValType.getObjCLifetime()) {
1333   case Qualifiers::OCL_None:
1334   case Qualifiers::OCL_ExplicitNone:
1335     // okay
1336     break;
1337
1338   case Qualifiers::OCL_Weak:
1339   case Qualifiers::OCL_Strong:
1340   case Qualifiers::OCL_Autoreleasing:
1341     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1342       << ValType << PointerArg->getSourceRange();
1343     return true;
1344   }
1345
1346   if (IsLdrex) {
1347     TheCall->setType(ValType);
1348     return false;
1349   }
1350
1351   // Initialize the argument to be stored.
1352   ExprResult ValArg = TheCall->getArg(0);
1353   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1354       Context, ValType, /*consume*/ false);
1355   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1356   if (ValArg.isInvalid())
1357     return true;
1358   TheCall->setArg(0, ValArg.get());
1359
1360   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1361   // but the custom checker bypasses all default analysis.
1362   TheCall->setType(Context.IntTy);
1363   return false;
1364 }
1365
1366 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1367   llvm::APSInt Result;
1368
1369   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1370       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371       BuiltinID == ARM::BI__builtin_arm_strex ||
1372       BuiltinID == ARM::BI__builtin_arm_stlex) {
1373     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1374   }
1375
1376   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1377     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1378       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1379   }
1380
1381   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1382       BuiltinID == ARM::BI__builtin_arm_wsr64)
1383     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1384
1385   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1386       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1387       BuiltinID == ARM::BI__builtin_arm_wsr ||
1388       BuiltinID == ARM::BI__builtin_arm_wsrp)
1389     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1390
1391   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1392     return true;
1393
1394   // For intrinsics which take an immediate value as part of the instruction,
1395   // range check them here.
1396   unsigned i = 0, l = 0, u = 0;
1397   switch (BuiltinID) {
1398   default: return false;
1399   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1400   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1401   case ARM::BI__builtin_arm_vcvtr_f:
1402   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1403   case ARM::BI__builtin_arm_dmb:
1404   case ARM::BI__builtin_arm_dsb:
1405   case ARM::BI__builtin_arm_isb:
1406   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1407   }
1408
1409   // FIXME: VFP Intrinsics should error if VFP not present.
1410   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1411 }
1412
1413 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1414                                          CallExpr *TheCall) {
1415   llvm::APSInt Result;
1416
1417   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1418       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1419       BuiltinID == AArch64::BI__builtin_arm_strex ||
1420       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1421     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1422   }
1423
1424   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1425     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1426       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1427       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1428       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1429   }
1430
1431   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1432       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1433     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1434
1435   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1436       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1437       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1438       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1439     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1440
1441   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1442     return true;
1443
1444   // For intrinsics which take an immediate value as part of the instruction,
1445   // range check them here.
1446   unsigned i = 0, l = 0, u = 0;
1447   switch (BuiltinID) {
1448   default: return false;
1449   case AArch64::BI__builtin_arm_dmb:
1450   case AArch64::BI__builtin_arm_dsb:
1451   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1452   }
1453
1454   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1455 }
1456
1457 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1458 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1459 // ordering for DSP is unspecified. MSA is ordered by the data format used
1460 // by the underlying instruction i.e., df/m, df/n and then by size.
1461 //
1462 // FIXME: The size tests here should instead be tablegen'd along with the
1463 //        definitions from include/clang/Basic/BuiltinsMips.def.
1464 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1465 //        be too.
1466 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1467   unsigned i = 0, l = 0, u = 0, m = 0;
1468   switch (BuiltinID) {
1469   default: return false;
1470   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1471   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1472   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1473   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1474   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1475   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1476   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1477   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1478   // df/m field.
1479   // These intrinsics take an unsigned 3 bit immediate.
1480   case Mips::BI__builtin_msa_bclri_b:
1481   case Mips::BI__builtin_msa_bnegi_b:
1482   case Mips::BI__builtin_msa_bseti_b:
1483   case Mips::BI__builtin_msa_sat_s_b:
1484   case Mips::BI__builtin_msa_sat_u_b:
1485   case Mips::BI__builtin_msa_slli_b:
1486   case Mips::BI__builtin_msa_srai_b:
1487   case Mips::BI__builtin_msa_srari_b:
1488   case Mips::BI__builtin_msa_srli_b:
1489   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1490   case Mips::BI__builtin_msa_binsli_b:
1491   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1492   // These intrinsics take an unsigned 4 bit immediate.
1493   case Mips::BI__builtin_msa_bclri_h:
1494   case Mips::BI__builtin_msa_bnegi_h:
1495   case Mips::BI__builtin_msa_bseti_h:
1496   case Mips::BI__builtin_msa_sat_s_h:
1497   case Mips::BI__builtin_msa_sat_u_h:
1498   case Mips::BI__builtin_msa_slli_h:
1499   case Mips::BI__builtin_msa_srai_h:
1500   case Mips::BI__builtin_msa_srari_h:
1501   case Mips::BI__builtin_msa_srli_h:
1502   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1503   case Mips::BI__builtin_msa_binsli_h:
1504   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1505   // These intrinsics take an unsigned 5 bit immedate.
1506   // The first block of intrinsics actually have an unsigned 5 bit field,
1507   // not a df/n field.
1508   case Mips::BI__builtin_msa_clei_u_b:
1509   case Mips::BI__builtin_msa_clei_u_h:
1510   case Mips::BI__builtin_msa_clei_u_w:
1511   case Mips::BI__builtin_msa_clei_u_d:
1512   case Mips::BI__builtin_msa_clti_u_b:
1513   case Mips::BI__builtin_msa_clti_u_h:
1514   case Mips::BI__builtin_msa_clti_u_w:
1515   case Mips::BI__builtin_msa_clti_u_d:
1516   case Mips::BI__builtin_msa_maxi_u_b:
1517   case Mips::BI__builtin_msa_maxi_u_h:
1518   case Mips::BI__builtin_msa_maxi_u_w:
1519   case Mips::BI__builtin_msa_maxi_u_d:
1520   case Mips::BI__builtin_msa_mini_u_b:
1521   case Mips::BI__builtin_msa_mini_u_h:
1522   case Mips::BI__builtin_msa_mini_u_w:
1523   case Mips::BI__builtin_msa_mini_u_d:
1524   case Mips::BI__builtin_msa_addvi_b:
1525   case Mips::BI__builtin_msa_addvi_h:
1526   case Mips::BI__builtin_msa_addvi_w:
1527   case Mips::BI__builtin_msa_addvi_d:
1528   case Mips::BI__builtin_msa_bclri_w:
1529   case Mips::BI__builtin_msa_bnegi_w:
1530   case Mips::BI__builtin_msa_bseti_w:
1531   case Mips::BI__builtin_msa_sat_s_w:
1532   case Mips::BI__builtin_msa_sat_u_w:
1533   case Mips::BI__builtin_msa_slli_w:
1534   case Mips::BI__builtin_msa_srai_w:
1535   case Mips::BI__builtin_msa_srari_w:
1536   case Mips::BI__builtin_msa_srli_w:
1537   case Mips::BI__builtin_msa_srlri_w:
1538   case Mips::BI__builtin_msa_subvi_b:
1539   case Mips::BI__builtin_msa_subvi_h:
1540   case Mips::BI__builtin_msa_subvi_w:
1541   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1542   case Mips::BI__builtin_msa_binsli_w:
1543   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1544   // These intrinsics take an unsigned 6 bit immediate.
1545   case Mips::BI__builtin_msa_bclri_d:
1546   case Mips::BI__builtin_msa_bnegi_d:
1547   case Mips::BI__builtin_msa_bseti_d:
1548   case Mips::BI__builtin_msa_sat_s_d:
1549   case Mips::BI__builtin_msa_sat_u_d:
1550   case Mips::BI__builtin_msa_slli_d:
1551   case Mips::BI__builtin_msa_srai_d:
1552   case Mips::BI__builtin_msa_srari_d:
1553   case Mips::BI__builtin_msa_srli_d:
1554   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1555   case Mips::BI__builtin_msa_binsli_d:
1556   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1557   // These intrinsics take a signed 5 bit immediate.
1558   case Mips::BI__builtin_msa_ceqi_b:
1559   case Mips::BI__builtin_msa_ceqi_h:
1560   case Mips::BI__builtin_msa_ceqi_w:
1561   case Mips::BI__builtin_msa_ceqi_d:
1562   case Mips::BI__builtin_msa_clti_s_b:
1563   case Mips::BI__builtin_msa_clti_s_h:
1564   case Mips::BI__builtin_msa_clti_s_w:
1565   case Mips::BI__builtin_msa_clti_s_d:
1566   case Mips::BI__builtin_msa_clei_s_b:
1567   case Mips::BI__builtin_msa_clei_s_h:
1568   case Mips::BI__builtin_msa_clei_s_w:
1569   case Mips::BI__builtin_msa_clei_s_d:
1570   case Mips::BI__builtin_msa_maxi_s_b:
1571   case Mips::BI__builtin_msa_maxi_s_h:
1572   case Mips::BI__builtin_msa_maxi_s_w:
1573   case Mips::BI__builtin_msa_maxi_s_d:
1574   case Mips::BI__builtin_msa_mini_s_b:
1575   case Mips::BI__builtin_msa_mini_s_h:
1576   case Mips::BI__builtin_msa_mini_s_w:
1577   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1578   // These intrinsics take an unsigned 8 bit immediate.
1579   case Mips::BI__builtin_msa_andi_b:
1580   case Mips::BI__builtin_msa_nori_b:
1581   case Mips::BI__builtin_msa_ori_b:
1582   case Mips::BI__builtin_msa_shf_b:
1583   case Mips::BI__builtin_msa_shf_h:
1584   case Mips::BI__builtin_msa_shf_w:
1585   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1586   case Mips::BI__builtin_msa_bseli_b:
1587   case Mips::BI__builtin_msa_bmnzi_b:
1588   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1589   // df/n format
1590   // These intrinsics take an unsigned 4 bit immediate.
1591   case Mips::BI__builtin_msa_copy_s_b:
1592   case Mips::BI__builtin_msa_copy_u_b:
1593   case Mips::BI__builtin_msa_insve_b:
1594   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1595   case Mips::BI__builtin_msa_sld_b:
1596   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1597   // These intrinsics take an unsigned 3 bit immediate.
1598   case Mips::BI__builtin_msa_copy_s_h:
1599   case Mips::BI__builtin_msa_copy_u_h:
1600   case Mips::BI__builtin_msa_insve_h:
1601   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1602   case Mips::BI__builtin_msa_sld_h:
1603   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1604   // These intrinsics take an unsigned 2 bit immediate.
1605   case Mips::BI__builtin_msa_copy_s_w:
1606   case Mips::BI__builtin_msa_copy_u_w:
1607   case Mips::BI__builtin_msa_insve_w:
1608   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1609   case Mips::BI__builtin_msa_sld_w:
1610   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1611   // These intrinsics take an unsigned 1 bit immediate.
1612   case Mips::BI__builtin_msa_copy_s_d:
1613   case Mips::BI__builtin_msa_copy_u_d:
1614   case Mips::BI__builtin_msa_insve_d:
1615   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1616   case Mips::BI__builtin_msa_sld_d:
1617   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1618   // Memory offsets and immediate loads.
1619   // These intrinsics take a signed 10 bit immediate.
1620   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1621   case Mips::BI__builtin_msa_ldi_h:
1622   case Mips::BI__builtin_msa_ldi_w:
1623   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1624   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1625   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1626   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1627   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1628   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1629   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1630   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1631   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1632   }
1633
1634   if (!m)
1635     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1636
1637   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1638          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1639 }
1640
1641 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1642   unsigned i = 0, l = 0, u = 0;
1643   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1644                       BuiltinID == PPC::BI__builtin_divdeu ||
1645                       BuiltinID == PPC::BI__builtin_bpermd;
1646   bool IsTarget64Bit = Context.getTargetInfo()
1647                               .getTypeWidth(Context
1648                                             .getTargetInfo()
1649                                             .getIntPtrType()) == 64;
1650   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1651                        BuiltinID == PPC::BI__builtin_divweu ||
1652                        BuiltinID == PPC::BI__builtin_divde ||
1653                        BuiltinID == PPC::BI__builtin_divdeu;
1654
1655   if (Is64BitBltin && !IsTarget64Bit)
1656       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1657              << TheCall->getSourceRange();
1658
1659   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1660       (BuiltinID == PPC::BI__builtin_bpermd &&
1661        !Context.getTargetInfo().hasFeature("bpermd")))
1662     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1663            << TheCall->getSourceRange();
1664
1665   switch (BuiltinID) {
1666   default: return false;
1667   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1668   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1669     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1670            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1671   case PPC::BI__builtin_tbegin:
1672   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1673   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1674   case PPC::BI__builtin_tabortwc:
1675   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1676   case PPC::BI__builtin_tabortwci:
1677   case PPC::BI__builtin_tabortdci:
1678     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1679            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1680   }
1681   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1682 }
1683
1684 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1685                                            CallExpr *TheCall) {
1686   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1687     Expr *Arg = TheCall->getArg(0);
1688     llvm::APSInt AbortCode(32);
1689     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1690         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1691       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1692              << Arg->getSourceRange();
1693   }
1694
1695   // For intrinsics which take an immediate value as part of the instruction,
1696   // range check them here.
1697   unsigned i = 0, l = 0, u = 0;
1698   switch (BuiltinID) {
1699   default: return false;
1700   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1701   case SystemZ::BI__builtin_s390_verimb:
1702   case SystemZ::BI__builtin_s390_verimh:
1703   case SystemZ::BI__builtin_s390_verimf:
1704   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1705   case SystemZ::BI__builtin_s390_vfaeb:
1706   case SystemZ::BI__builtin_s390_vfaeh:
1707   case SystemZ::BI__builtin_s390_vfaef:
1708   case SystemZ::BI__builtin_s390_vfaebs:
1709   case SystemZ::BI__builtin_s390_vfaehs:
1710   case SystemZ::BI__builtin_s390_vfaefs:
1711   case SystemZ::BI__builtin_s390_vfaezb:
1712   case SystemZ::BI__builtin_s390_vfaezh:
1713   case SystemZ::BI__builtin_s390_vfaezf:
1714   case SystemZ::BI__builtin_s390_vfaezbs:
1715   case SystemZ::BI__builtin_s390_vfaezhs:
1716   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1717   case SystemZ::BI__builtin_s390_vfidb:
1718     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1719            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1720   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1721   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1722   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1723   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1724   case SystemZ::BI__builtin_s390_vstrcb:
1725   case SystemZ::BI__builtin_s390_vstrch:
1726   case SystemZ::BI__builtin_s390_vstrcf:
1727   case SystemZ::BI__builtin_s390_vstrczb:
1728   case SystemZ::BI__builtin_s390_vstrczh:
1729   case SystemZ::BI__builtin_s390_vstrczf:
1730   case SystemZ::BI__builtin_s390_vstrcbs:
1731   case SystemZ::BI__builtin_s390_vstrchs:
1732   case SystemZ::BI__builtin_s390_vstrcfs:
1733   case SystemZ::BI__builtin_s390_vstrczbs:
1734   case SystemZ::BI__builtin_s390_vstrczhs:
1735   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1736   }
1737   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1738 }
1739
1740 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1741 /// This checks that the target supports __builtin_cpu_supports and
1742 /// that the string argument is constant and valid.
1743 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1744   Expr *Arg = TheCall->getArg(0);
1745
1746   // Check if the argument is a string literal.
1747   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1748     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1749            << Arg->getSourceRange();
1750
1751   // Check the contents of the string.
1752   StringRef Feature =
1753       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1754   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1755     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1756            << Arg->getSourceRange();
1757   return false;
1758 }
1759
1760 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1761   int i = 0, l = 0, u = 0;
1762   switch (BuiltinID) {
1763   default:
1764     return false;
1765   case X86::BI__builtin_cpu_supports:
1766     return SemaBuiltinCpuSupports(*this, TheCall);
1767   case X86::BI__builtin_ms_va_start:
1768     return SemaBuiltinMSVAStart(TheCall);
1769   case X86::BI__builtin_ia32_extractf64x4_mask:
1770   case X86::BI__builtin_ia32_extracti64x4_mask:
1771   case X86::BI__builtin_ia32_extractf32x8_mask:
1772   case X86::BI__builtin_ia32_extracti32x8_mask:
1773   case X86::BI__builtin_ia32_extractf64x2_256_mask:
1774   case X86::BI__builtin_ia32_extracti64x2_256_mask:
1775   case X86::BI__builtin_ia32_extractf32x4_256_mask:
1776   case X86::BI__builtin_ia32_extracti32x4_256_mask:
1777     i = 1; l = 0; u = 1;
1778     break;
1779   case X86::BI_mm_prefetch:
1780   case X86::BI__builtin_ia32_extractf32x4_mask:
1781   case X86::BI__builtin_ia32_extracti32x4_mask:
1782   case X86::BI__builtin_ia32_extractf64x2_512_mask:
1783   case X86::BI__builtin_ia32_extracti64x2_512_mask:
1784     i = 1; l = 0; u = 3;
1785     break;
1786   case X86::BI__builtin_ia32_insertf32x8_mask:
1787   case X86::BI__builtin_ia32_inserti32x8_mask:
1788   case X86::BI__builtin_ia32_insertf64x4_mask:
1789   case X86::BI__builtin_ia32_inserti64x4_mask:
1790   case X86::BI__builtin_ia32_insertf64x2_256_mask:
1791   case X86::BI__builtin_ia32_inserti64x2_256_mask:
1792   case X86::BI__builtin_ia32_insertf32x4_256_mask:
1793   case X86::BI__builtin_ia32_inserti32x4_256_mask:
1794     i = 2; l = 0; u = 1;
1795     break;
1796   case X86::BI__builtin_ia32_sha1rnds4:
1797   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1798   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1799   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1800   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1801   case X86::BI__builtin_ia32_insertf64x2_512_mask:
1802   case X86::BI__builtin_ia32_inserti64x2_512_mask:
1803   case X86::BI__builtin_ia32_insertf32x4_mask:
1804   case X86::BI__builtin_ia32_inserti32x4_mask:
1805     i = 2; l = 0; u = 3;
1806     break;
1807   case X86::BI__builtin_ia32_vpermil2pd:
1808   case X86::BI__builtin_ia32_vpermil2pd256:
1809   case X86::BI__builtin_ia32_vpermil2ps:
1810   case X86::BI__builtin_ia32_vpermil2ps256:
1811     i = 3; l = 0; u = 3;
1812     break;
1813   case X86::BI__builtin_ia32_cmpb128_mask:
1814   case X86::BI__builtin_ia32_cmpw128_mask:
1815   case X86::BI__builtin_ia32_cmpd128_mask:
1816   case X86::BI__builtin_ia32_cmpq128_mask:
1817   case X86::BI__builtin_ia32_cmpb256_mask:
1818   case X86::BI__builtin_ia32_cmpw256_mask:
1819   case X86::BI__builtin_ia32_cmpd256_mask:
1820   case X86::BI__builtin_ia32_cmpq256_mask:
1821   case X86::BI__builtin_ia32_cmpb512_mask:
1822   case X86::BI__builtin_ia32_cmpw512_mask:
1823   case X86::BI__builtin_ia32_cmpd512_mask:
1824   case X86::BI__builtin_ia32_cmpq512_mask:
1825   case X86::BI__builtin_ia32_ucmpb128_mask:
1826   case X86::BI__builtin_ia32_ucmpw128_mask:
1827   case X86::BI__builtin_ia32_ucmpd128_mask:
1828   case X86::BI__builtin_ia32_ucmpq128_mask:
1829   case X86::BI__builtin_ia32_ucmpb256_mask:
1830   case X86::BI__builtin_ia32_ucmpw256_mask:
1831   case X86::BI__builtin_ia32_ucmpd256_mask:
1832   case X86::BI__builtin_ia32_ucmpq256_mask:
1833   case X86::BI__builtin_ia32_ucmpb512_mask:
1834   case X86::BI__builtin_ia32_ucmpw512_mask:
1835   case X86::BI__builtin_ia32_ucmpd512_mask:
1836   case X86::BI__builtin_ia32_ucmpq512_mask:
1837   case X86::BI__builtin_ia32_vpcomub:
1838   case X86::BI__builtin_ia32_vpcomuw:
1839   case X86::BI__builtin_ia32_vpcomud:
1840   case X86::BI__builtin_ia32_vpcomuq:
1841   case X86::BI__builtin_ia32_vpcomb:
1842   case X86::BI__builtin_ia32_vpcomw:
1843   case X86::BI__builtin_ia32_vpcomd:
1844   case X86::BI__builtin_ia32_vpcomq:
1845     i = 2; l = 0; u = 7;
1846     break;
1847   case X86::BI__builtin_ia32_roundps:
1848   case X86::BI__builtin_ia32_roundpd:
1849   case X86::BI__builtin_ia32_roundps256:
1850   case X86::BI__builtin_ia32_roundpd256:
1851     i = 1; l = 0; u = 15;
1852     break;
1853   case X86::BI__builtin_ia32_roundss:
1854   case X86::BI__builtin_ia32_roundsd:
1855   case X86::BI__builtin_ia32_rangepd128_mask:
1856   case X86::BI__builtin_ia32_rangepd256_mask:
1857   case X86::BI__builtin_ia32_rangepd512_mask:
1858   case X86::BI__builtin_ia32_rangeps128_mask:
1859   case X86::BI__builtin_ia32_rangeps256_mask:
1860   case X86::BI__builtin_ia32_rangeps512_mask:
1861   case X86::BI__builtin_ia32_getmantsd_round_mask:
1862   case X86::BI__builtin_ia32_getmantss_round_mask:
1863     i = 2; l = 0; u = 15;
1864     break;
1865   case X86::BI__builtin_ia32_cmpps:
1866   case X86::BI__builtin_ia32_cmpss:
1867   case X86::BI__builtin_ia32_cmppd:
1868   case X86::BI__builtin_ia32_cmpsd:
1869   case X86::BI__builtin_ia32_cmpps256:
1870   case X86::BI__builtin_ia32_cmppd256:
1871   case X86::BI__builtin_ia32_cmpps128_mask:
1872   case X86::BI__builtin_ia32_cmppd128_mask:
1873   case X86::BI__builtin_ia32_cmpps256_mask:
1874   case X86::BI__builtin_ia32_cmppd256_mask:
1875   case X86::BI__builtin_ia32_cmpps512_mask:
1876   case X86::BI__builtin_ia32_cmppd512_mask:
1877   case X86::BI__builtin_ia32_cmpsd_mask:
1878   case X86::BI__builtin_ia32_cmpss_mask:
1879     i = 2; l = 0; u = 31;
1880     break;
1881   case X86::BI__builtin_ia32_xabort:
1882     i = 0; l = -128; u = 255;
1883     break;
1884   case X86::BI__builtin_ia32_pshufw:
1885   case X86::BI__builtin_ia32_aeskeygenassist128:
1886     i = 1; l = -128; u = 255;
1887     break;
1888   case X86::BI__builtin_ia32_vcvtps2ph:
1889   case X86::BI__builtin_ia32_vcvtps2ph256:
1890   case X86::BI__builtin_ia32_rndscaleps_128_mask:
1891   case X86::BI__builtin_ia32_rndscalepd_128_mask:
1892   case X86::BI__builtin_ia32_rndscaleps_256_mask:
1893   case X86::BI__builtin_ia32_rndscalepd_256_mask:
1894   case X86::BI__builtin_ia32_rndscaleps_mask:
1895   case X86::BI__builtin_ia32_rndscalepd_mask:
1896   case X86::BI__builtin_ia32_reducepd128_mask:
1897   case X86::BI__builtin_ia32_reducepd256_mask:
1898   case X86::BI__builtin_ia32_reducepd512_mask:
1899   case X86::BI__builtin_ia32_reduceps128_mask:
1900   case X86::BI__builtin_ia32_reduceps256_mask:
1901   case X86::BI__builtin_ia32_reduceps512_mask:
1902   case X86::BI__builtin_ia32_prold512_mask:
1903   case X86::BI__builtin_ia32_prolq512_mask:
1904   case X86::BI__builtin_ia32_prold128_mask:
1905   case X86::BI__builtin_ia32_prold256_mask:
1906   case X86::BI__builtin_ia32_prolq128_mask:
1907   case X86::BI__builtin_ia32_prolq256_mask:
1908   case X86::BI__builtin_ia32_prord128_mask:
1909   case X86::BI__builtin_ia32_prord256_mask:
1910   case X86::BI__builtin_ia32_prorq128_mask:
1911   case X86::BI__builtin_ia32_prorq256_mask:
1912   case X86::BI__builtin_ia32_psllwi512_mask:
1913   case X86::BI__builtin_ia32_psllwi128_mask:
1914   case X86::BI__builtin_ia32_psllwi256_mask:
1915   case X86::BI__builtin_ia32_psrldi128_mask:
1916   case X86::BI__builtin_ia32_psrldi256_mask:
1917   case X86::BI__builtin_ia32_psrldi512_mask:
1918   case X86::BI__builtin_ia32_psrlqi128_mask:
1919   case X86::BI__builtin_ia32_psrlqi256_mask:
1920   case X86::BI__builtin_ia32_psrlqi512_mask:
1921   case X86::BI__builtin_ia32_psrawi512_mask:
1922   case X86::BI__builtin_ia32_psrawi128_mask:
1923   case X86::BI__builtin_ia32_psrawi256_mask:
1924   case X86::BI__builtin_ia32_psrlwi512_mask:
1925   case X86::BI__builtin_ia32_psrlwi128_mask:
1926   case X86::BI__builtin_ia32_psrlwi256_mask:
1927   case X86::BI__builtin_ia32_psradi128_mask:
1928   case X86::BI__builtin_ia32_psradi256_mask:
1929   case X86::BI__builtin_ia32_psradi512_mask:
1930   case X86::BI__builtin_ia32_psraqi128_mask:
1931   case X86::BI__builtin_ia32_psraqi256_mask:
1932   case X86::BI__builtin_ia32_psraqi512_mask:
1933   case X86::BI__builtin_ia32_pslldi128_mask:
1934   case X86::BI__builtin_ia32_pslldi256_mask:
1935   case X86::BI__builtin_ia32_pslldi512_mask:
1936   case X86::BI__builtin_ia32_psllqi128_mask:
1937   case X86::BI__builtin_ia32_psllqi256_mask:
1938   case X86::BI__builtin_ia32_psllqi512_mask:
1939   case X86::BI__builtin_ia32_fpclasspd128_mask:
1940   case X86::BI__builtin_ia32_fpclasspd256_mask:
1941   case X86::BI__builtin_ia32_fpclassps128_mask:
1942   case X86::BI__builtin_ia32_fpclassps256_mask:
1943   case X86::BI__builtin_ia32_fpclassps512_mask:
1944   case X86::BI__builtin_ia32_fpclasspd512_mask:
1945   case X86::BI__builtin_ia32_fpclasssd_mask:
1946   case X86::BI__builtin_ia32_fpclassss_mask:
1947     i = 1; l = 0; u = 255;
1948     break;
1949   case X86::BI__builtin_ia32_palignr:
1950   case X86::BI__builtin_ia32_insertps128:
1951   case X86::BI__builtin_ia32_dpps:
1952   case X86::BI__builtin_ia32_dppd:
1953   case X86::BI__builtin_ia32_dpps256:
1954   case X86::BI__builtin_ia32_mpsadbw128:
1955   case X86::BI__builtin_ia32_mpsadbw256:
1956   case X86::BI__builtin_ia32_pcmpistrm128:
1957   case X86::BI__builtin_ia32_pcmpistri128:
1958   case X86::BI__builtin_ia32_pcmpistria128:
1959   case X86::BI__builtin_ia32_pcmpistric128:
1960   case X86::BI__builtin_ia32_pcmpistrio128:
1961   case X86::BI__builtin_ia32_pcmpistris128:
1962   case X86::BI__builtin_ia32_pcmpistriz128:
1963   case X86::BI__builtin_ia32_pclmulqdq128:
1964   case X86::BI__builtin_ia32_vperm2f128_pd256:
1965   case X86::BI__builtin_ia32_vperm2f128_ps256:
1966   case X86::BI__builtin_ia32_vperm2f128_si256:
1967   case X86::BI__builtin_ia32_permti256:
1968     i = 2; l = -128; u = 255;
1969     break;
1970   case X86::BI__builtin_ia32_palignr128:
1971   case X86::BI__builtin_ia32_palignr256:
1972   case X86::BI__builtin_ia32_palignr128_mask:
1973   case X86::BI__builtin_ia32_palignr256_mask:
1974   case X86::BI__builtin_ia32_palignr512_mask:
1975   case X86::BI__builtin_ia32_alignq512_mask:
1976   case X86::BI__builtin_ia32_alignd512_mask:
1977   case X86::BI__builtin_ia32_alignd128_mask:
1978   case X86::BI__builtin_ia32_alignd256_mask:
1979   case X86::BI__builtin_ia32_alignq128_mask:
1980   case X86::BI__builtin_ia32_alignq256_mask:
1981   case X86::BI__builtin_ia32_vcomisd:
1982   case X86::BI__builtin_ia32_vcomiss:
1983   case X86::BI__builtin_ia32_shuf_f32x4_mask:
1984   case X86::BI__builtin_ia32_shuf_f64x2_mask:
1985   case X86::BI__builtin_ia32_shuf_i32x4_mask:
1986   case X86::BI__builtin_ia32_shuf_i64x2_mask:
1987   case X86::BI__builtin_ia32_dbpsadbw128_mask:
1988   case X86::BI__builtin_ia32_dbpsadbw256_mask:
1989   case X86::BI__builtin_ia32_dbpsadbw512_mask:
1990     i = 2; l = 0; u = 255;
1991     break;
1992   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1993   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1994   case X86::BI__builtin_ia32_fixupimmps512_mask:
1995   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1996   case X86::BI__builtin_ia32_fixupimmsd_mask:
1997   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1998   case X86::BI__builtin_ia32_fixupimmss_mask:
1999   case X86::BI__builtin_ia32_fixupimmss_maskz:
2000   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2001   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2002   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2003   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2004   case X86::BI__builtin_ia32_fixupimmps128_mask:
2005   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2006   case X86::BI__builtin_ia32_fixupimmps256_mask:
2007   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2008   case X86::BI__builtin_ia32_pternlogd512_mask:
2009   case X86::BI__builtin_ia32_pternlogd512_maskz:
2010   case X86::BI__builtin_ia32_pternlogq512_mask:
2011   case X86::BI__builtin_ia32_pternlogq512_maskz:
2012   case X86::BI__builtin_ia32_pternlogd128_mask:
2013   case X86::BI__builtin_ia32_pternlogd128_maskz:
2014   case X86::BI__builtin_ia32_pternlogd256_mask:
2015   case X86::BI__builtin_ia32_pternlogd256_maskz:
2016   case X86::BI__builtin_ia32_pternlogq128_mask:
2017   case X86::BI__builtin_ia32_pternlogq128_maskz:
2018   case X86::BI__builtin_ia32_pternlogq256_mask:
2019   case X86::BI__builtin_ia32_pternlogq256_maskz:
2020     i = 3; l = 0; u = 255;
2021     break;
2022   case X86::BI__builtin_ia32_pcmpestrm128:
2023   case X86::BI__builtin_ia32_pcmpestri128:
2024   case X86::BI__builtin_ia32_pcmpestria128:
2025   case X86::BI__builtin_ia32_pcmpestric128:
2026   case X86::BI__builtin_ia32_pcmpestrio128:
2027   case X86::BI__builtin_ia32_pcmpestris128:
2028   case X86::BI__builtin_ia32_pcmpestriz128:
2029     i = 4; l = -128; u = 255;
2030     break;
2031   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2032   case X86::BI__builtin_ia32_rndscaless_round_mask:
2033     i = 4; l = 0; u = 255;
2034     break;
2035   }
2036   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2037 }
2038
2039 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2040 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2041 /// Returns true when the format fits the function and the FormatStringInfo has
2042 /// been populated.
2043 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2044                                FormatStringInfo *FSI) {
2045   FSI->HasVAListArg = Format->getFirstArg() == 0;
2046   FSI->FormatIdx = Format->getFormatIdx() - 1;
2047   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2048
2049   // The way the format attribute works in GCC, the implicit this argument
2050   // of member functions is counted. However, it doesn't appear in our own
2051   // lists, so decrement format_idx in that case.
2052   if (IsCXXMember) {
2053     if(FSI->FormatIdx == 0)
2054       return false;
2055     --FSI->FormatIdx;
2056     if (FSI->FirstDataArg != 0)
2057       --FSI->FirstDataArg;
2058   }
2059   return true;
2060 }
2061
2062 /// Checks if a the given expression evaluates to null.
2063 ///
2064 /// \brief Returns true if the value evaluates to null.
2065 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2066   // If the expression has non-null type, it doesn't evaluate to null.
2067   if (auto nullability
2068         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2069     if (*nullability == NullabilityKind::NonNull)
2070       return false;
2071   }
2072
2073   // As a special case, transparent unions initialized with zero are
2074   // considered null for the purposes of the nonnull attribute.
2075   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2076     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2077       if (const CompoundLiteralExpr *CLE =
2078           dyn_cast<CompoundLiteralExpr>(Expr))
2079         if (const InitListExpr *ILE =
2080             dyn_cast<InitListExpr>(CLE->getInitializer()))
2081           Expr = ILE->getInit(0);
2082   }
2083
2084   bool Result;
2085   return (!Expr->isValueDependent() &&
2086           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2087           !Result);
2088 }
2089
2090 static void CheckNonNullArgument(Sema &S,
2091                                  const Expr *ArgExpr,
2092                                  SourceLocation CallSiteLoc) {
2093   if (CheckNonNullExpr(S, ArgExpr))
2094     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2095            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2096 }
2097
2098 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2099   FormatStringInfo FSI;
2100   if ((GetFormatStringType(Format) == FST_NSString) &&
2101       getFormatStringInfo(Format, false, &FSI)) {
2102     Idx = FSI.FormatIdx;
2103     return true;
2104   }
2105   return false;
2106 }
2107 /// \brief Diagnose use of %s directive in an NSString which is being passed
2108 /// as formatting string to formatting method.
2109 static void
2110 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2111                                         const NamedDecl *FDecl,
2112                                         Expr **Args,
2113                                         unsigned NumArgs) {
2114   unsigned Idx = 0;
2115   bool Format = false;
2116   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2117   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2118     Idx = 2;
2119     Format = true;
2120   }
2121   else
2122     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2123       if (S.GetFormatNSStringIdx(I, Idx)) {
2124         Format = true;
2125         break;
2126       }
2127     }
2128   if (!Format || NumArgs <= Idx)
2129     return;
2130   const Expr *FormatExpr = Args[Idx];
2131   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2132     FormatExpr = CSCE->getSubExpr();
2133   const StringLiteral *FormatString;
2134   if (const ObjCStringLiteral *OSL =
2135       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2136     FormatString = OSL->getString();
2137   else
2138     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2139   if (!FormatString)
2140     return;
2141   if (S.FormatStringHasSArg(FormatString)) {
2142     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2143       << "%s" << 1 << 1;
2144     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2145       << FDecl->getDeclName();
2146   }
2147 }
2148
2149 /// Determine whether the given type has a non-null nullability annotation.
2150 static bool isNonNullType(ASTContext &ctx, QualType type) {
2151   if (auto nullability = type->getNullability(ctx))
2152     return *nullability == NullabilityKind::NonNull;
2153      
2154   return false;
2155 }
2156
2157 static void CheckNonNullArguments(Sema &S,
2158                                   const NamedDecl *FDecl,
2159                                   const FunctionProtoType *Proto,
2160                                   ArrayRef<const Expr *> Args,
2161                                   SourceLocation CallSiteLoc) {
2162   assert((FDecl || Proto) && "Need a function declaration or prototype");
2163
2164   // Check the attributes attached to the method/function itself.
2165   llvm::SmallBitVector NonNullArgs;
2166   if (FDecl) {
2167     // Handle the nonnull attribute on the function/method declaration itself.
2168     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2169       if (!NonNull->args_size()) {
2170         // Easy case: all pointer arguments are nonnull.
2171         for (const auto *Arg : Args)
2172           if (S.isValidPointerAttrType(Arg->getType()))
2173             CheckNonNullArgument(S, Arg, CallSiteLoc);
2174         return;
2175       }
2176
2177       for (unsigned Val : NonNull->args()) {
2178         if (Val >= Args.size())
2179           continue;
2180         if (NonNullArgs.empty())
2181           NonNullArgs.resize(Args.size());
2182         NonNullArgs.set(Val);
2183       }
2184     }
2185   }
2186
2187   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2188     // Handle the nonnull attribute on the parameters of the
2189     // function/method.
2190     ArrayRef<ParmVarDecl*> parms;
2191     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2192       parms = FD->parameters();
2193     else
2194       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2195     
2196     unsigned ParamIndex = 0;
2197     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2198          I != E; ++I, ++ParamIndex) {
2199       const ParmVarDecl *PVD = *I;
2200       if (PVD->hasAttr<NonNullAttr>() || 
2201           isNonNullType(S.Context, PVD->getType())) {
2202         if (NonNullArgs.empty())
2203           NonNullArgs.resize(Args.size());
2204
2205         NonNullArgs.set(ParamIndex);
2206       }
2207     }
2208   } else {
2209     // If we have a non-function, non-method declaration but no
2210     // function prototype, try to dig out the function prototype.
2211     if (!Proto) {
2212       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2213         QualType type = VD->getType().getNonReferenceType();
2214         if (auto pointerType = type->getAs<PointerType>())
2215           type = pointerType->getPointeeType();
2216         else if (auto blockType = type->getAs<BlockPointerType>())
2217           type = blockType->getPointeeType();
2218         // FIXME: data member pointers?
2219
2220         // Dig out the function prototype, if there is one.
2221         Proto = type->getAs<FunctionProtoType>();
2222       } 
2223     }
2224
2225     // Fill in non-null argument information from the nullability
2226     // information on the parameter types (if we have them).
2227     if (Proto) {
2228       unsigned Index = 0;
2229       for (auto paramType : Proto->getParamTypes()) {
2230         if (isNonNullType(S.Context, paramType)) {
2231           if (NonNullArgs.empty())
2232             NonNullArgs.resize(Args.size());
2233           
2234           NonNullArgs.set(Index);
2235         }
2236         
2237         ++Index;
2238       }
2239     }
2240   }
2241
2242   // Check for non-null arguments.
2243   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 
2244        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2245     if (NonNullArgs[ArgIndex])
2246       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2247   }
2248 }
2249
2250 /// Handles the checks for format strings, non-POD arguments to vararg
2251 /// functions, and NULL arguments passed to non-NULL parameters.
2252 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2253                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2254                      SourceLocation Loc, SourceRange Range,
2255                      VariadicCallType CallType) {
2256   // FIXME: We should check as much as we can in the template definition.
2257   if (CurContext->isDependentContext())
2258     return;
2259
2260   // Printf and scanf checking.
2261   llvm::SmallBitVector CheckedVarArgs;
2262   if (FDecl) {
2263     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2264       // Only create vector if there are format attributes.
2265       CheckedVarArgs.resize(Args.size());
2266
2267       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2268                            CheckedVarArgs);
2269     }
2270   }
2271
2272   // Refuse POD arguments that weren't caught by the format string
2273   // checks above.
2274   if (CallType != VariadicDoesNotApply) {
2275     unsigned NumParams = Proto ? Proto->getNumParams()
2276                        : FDecl && isa<FunctionDecl>(FDecl)
2277                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2278                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2279                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2280                        : 0;
2281
2282     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2283       // Args[ArgIdx] can be null in malformed code.
2284       if (const Expr *Arg = Args[ArgIdx]) {
2285         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2286           checkVariadicArgument(Arg, CallType);
2287       }
2288     }
2289   }
2290
2291   if (FDecl || Proto) {
2292     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2293
2294     // Type safety checking.
2295     if (FDecl) {
2296       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2297         CheckArgumentWithTypeTag(I, Args.data());
2298     }
2299   }
2300 }
2301
2302 /// CheckConstructorCall - Check a constructor call for correctness and safety
2303 /// properties not enforced by the C type system.
2304 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2305                                 ArrayRef<const Expr *> Args,
2306                                 const FunctionProtoType *Proto,
2307                                 SourceLocation Loc) {
2308   VariadicCallType CallType =
2309     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2310   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 
2311             CallType);
2312 }
2313
2314 /// CheckFunctionCall - Check a direct function call for various correctness
2315 /// and safety properties not strictly enforced by the C type system.
2316 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2317                              const FunctionProtoType *Proto) {
2318   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2319                               isa<CXXMethodDecl>(FDecl);
2320   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2321                           IsMemberOperatorCall;
2322   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2323                                                   TheCall->getCallee());
2324   Expr** Args = TheCall->getArgs();
2325   unsigned NumArgs = TheCall->getNumArgs();
2326   if (IsMemberOperatorCall) {
2327     // If this is a call to a member operator, hide the first argument
2328     // from checkCall.
2329     // FIXME: Our choice of AST representation here is less than ideal.
2330     ++Args;
2331     --NumArgs;
2332   }
2333   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 
2334             IsMemberFunction, TheCall->getRParenLoc(),
2335             TheCall->getCallee()->getSourceRange(), CallType);
2336
2337   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2338   // None of the checks below are needed for functions that don't have
2339   // simple names (e.g., C++ conversion functions).
2340   if (!FnInfo)
2341     return false;
2342
2343   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2344   if (getLangOpts().ObjC1)
2345     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2346
2347   unsigned CMId = FDecl->getMemoryFunctionKind();
2348   if (CMId == 0)
2349     return false;
2350
2351   // Handle memory setting and copying functions.
2352   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2353     CheckStrlcpycatArguments(TheCall, FnInfo);
2354   else if (CMId == Builtin::BIstrncat)
2355     CheckStrncatArguments(TheCall, FnInfo);
2356   else
2357     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2358
2359   return false;
2360 }
2361
2362 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 
2363                                ArrayRef<const Expr *> Args) {
2364   VariadicCallType CallType =
2365       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2366
2367   checkCall(Method, nullptr, Args,
2368             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 
2369             CallType);
2370
2371   return false;
2372 }
2373
2374 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2375                             const FunctionProtoType *Proto) {
2376   QualType Ty;
2377   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2378     Ty = V->getType().getNonReferenceType();
2379   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2380     Ty = F->getType().getNonReferenceType();
2381   else
2382     return false;
2383
2384   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2385       !Ty->isFunctionProtoType())
2386     return false;
2387
2388   VariadicCallType CallType;
2389   if (!Proto || !Proto->isVariadic()) {
2390     CallType = VariadicDoesNotApply;
2391   } else if (Ty->isBlockPointerType()) {
2392     CallType = VariadicBlock;
2393   } else { // Ty->isFunctionPointerType()
2394     CallType = VariadicFunction;
2395   }
2396
2397   checkCall(NDecl, Proto,
2398             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2399             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2400             TheCall->getCallee()->getSourceRange(), CallType);
2401
2402   return false;
2403 }
2404
2405 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2406 /// such as function pointers returned from functions.
2407 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2408   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2409                                                   TheCall->getCallee());
2410   checkCall(/*FDecl=*/nullptr, Proto,
2411             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2412             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2413             TheCall->getCallee()->getSourceRange(), CallType);
2414
2415   return false;
2416 }
2417
2418 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2419   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2420     return false;
2421
2422   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2423   switch (Op) {
2424   case AtomicExpr::AO__c11_atomic_init:
2425     llvm_unreachable("There is no ordering argument for an init");
2426
2427   case AtomicExpr::AO__c11_atomic_load:
2428   case AtomicExpr::AO__atomic_load_n:
2429   case AtomicExpr::AO__atomic_load:
2430     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2431            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2432
2433   case AtomicExpr::AO__c11_atomic_store:
2434   case AtomicExpr::AO__atomic_store:
2435   case AtomicExpr::AO__atomic_store_n:
2436     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2437            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2438            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2439
2440   default:
2441     return true;
2442   }
2443 }
2444
2445 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2446                                          AtomicExpr::AtomicOp Op) {
2447   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2448   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2449
2450   // All these operations take one of the following forms:
2451   enum {
2452     // C    __c11_atomic_init(A *, C)
2453     Init,
2454     // C    __c11_atomic_load(A *, int)
2455     Load,
2456     // void __atomic_load(A *, CP, int)
2457     LoadCopy,
2458     // void __atomic_store(A *, CP, int)
2459     Copy,
2460     // C    __c11_atomic_add(A *, M, int)
2461     Arithmetic,
2462     // C    __atomic_exchange_n(A *, CP, int)
2463     Xchg,
2464     // void __atomic_exchange(A *, C *, CP, int)
2465     GNUXchg,
2466     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2467     C11CmpXchg,
2468     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2469     GNUCmpXchg
2470   } Form = Init;
2471   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2472   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2473   // where:
2474   //   C is an appropriate type,
2475   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2476   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2477   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2478   //   the int parameters are for orderings.
2479
2480   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2481                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2482                         AtomicExpr::AO__atomic_load,
2483                 "need to update code for modified C11 atomics");
2484   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2485                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2486   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2487              Op == AtomicExpr::AO__atomic_store_n ||
2488              Op == AtomicExpr::AO__atomic_exchange_n ||
2489              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2490   bool IsAddSub = false;
2491
2492   switch (Op) {
2493   case AtomicExpr::AO__c11_atomic_init:
2494     Form = Init;
2495     break;
2496
2497   case AtomicExpr::AO__c11_atomic_load:
2498   case AtomicExpr::AO__atomic_load_n:
2499     Form = Load;
2500     break;
2501
2502   case AtomicExpr::AO__atomic_load:
2503     Form = LoadCopy;
2504     break;
2505
2506   case AtomicExpr::AO__c11_atomic_store:
2507   case AtomicExpr::AO__atomic_store:
2508   case AtomicExpr::AO__atomic_store_n:
2509     Form = Copy;
2510     break;
2511
2512   case AtomicExpr::AO__c11_atomic_fetch_add:
2513   case AtomicExpr::AO__c11_atomic_fetch_sub:
2514   case AtomicExpr::AO__atomic_fetch_add:
2515   case AtomicExpr::AO__atomic_fetch_sub:
2516   case AtomicExpr::AO__atomic_add_fetch:
2517   case AtomicExpr::AO__atomic_sub_fetch:
2518     IsAddSub = true;
2519     // Fall through.
2520   case AtomicExpr::AO__c11_atomic_fetch_and:
2521   case AtomicExpr::AO__c11_atomic_fetch_or:
2522   case AtomicExpr::AO__c11_atomic_fetch_xor:
2523   case AtomicExpr::AO__atomic_fetch_and:
2524   case AtomicExpr::AO__atomic_fetch_or:
2525   case AtomicExpr::AO__atomic_fetch_xor:
2526   case AtomicExpr::AO__atomic_fetch_nand:
2527   case AtomicExpr::AO__atomic_and_fetch:
2528   case AtomicExpr::AO__atomic_or_fetch:
2529   case AtomicExpr::AO__atomic_xor_fetch:
2530   case AtomicExpr::AO__atomic_nand_fetch:
2531     Form = Arithmetic;
2532     break;
2533
2534   case AtomicExpr::AO__c11_atomic_exchange:
2535   case AtomicExpr::AO__atomic_exchange_n:
2536     Form = Xchg;
2537     break;
2538
2539   case AtomicExpr::AO__atomic_exchange:
2540     Form = GNUXchg;
2541     break;
2542
2543   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2544   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2545     Form = C11CmpXchg;
2546     break;
2547
2548   case AtomicExpr::AO__atomic_compare_exchange:
2549   case AtomicExpr::AO__atomic_compare_exchange_n:
2550     Form = GNUCmpXchg;
2551     break;
2552   }
2553
2554   // Check we have the right number of arguments.
2555   if (TheCall->getNumArgs() < NumArgs[Form]) {
2556     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2557       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2558       << TheCall->getCallee()->getSourceRange();
2559     return ExprError();
2560   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2561     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2562          diag::err_typecheck_call_too_many_args)
2563       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2564       << TheCall->getCallee()->getSourceRange();
2565     return ExprError();
2566   }
2567
2568   // Inspect the first argument of the atomic operation.
2569   Expr *Ptr = TheCall->getArg(0);
2570   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2571   if (ConvertedPtr.isInvalid())
2572     return ExprError();
2573
2574   Ptr = ConvertedPtr.get();
2575   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2576   if (!pointerType) {
2577     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2578       << Ptr->getType() << Ptr->getSourceRange();
2579     return ExprError();
2580   }
2581
2582   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2583   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2584   QualType ValType = AtomTy; // 'C'
2585   if (IsC11) {
2586     if (!AtomTy->isAtomicType()) {
2587       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2588         << Ptr->getType() << Ptr->getSourceRange();
2589       return ExprError();
2590     }
2591     if (AtomTy.isConstQualified()) {
2592       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2593         << Ptr->getType() << Ptr->getSourceRange();
2594       return ExprError();
2595     }
2596     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2597   } else if (Form != Load && Form != LoadCopy) {
2598     if (ValType.isConstQualified()) {
2599       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2600         << Ptr->getType() << Ptr->getSourceRange();
2601       return ExprError();
2602     }
2603   }
2604
2605   // For an arithmetic operation, the implied arithmetic must be well-formed.
2606   if (Form == Arithmetic) {
2607     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2608     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2609       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2610         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2611       return ExprError();
2612     }
2613     if (!IsAddSub && !ValType->isIntegerType()) {
2614       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2615         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2616       return ExprError();
2617     }
2618     if (IsC11 && ValType->isPointerType() &&
2619         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2620                             diag::err_incomplete_type)) {
2621       return ExprError();
2622     }
2623   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2624     // For __atomic_*_n operations, the value type must be a scalar integral or
2625     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2626     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2627       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2628     return ExprError();
2629   }
2630
2631   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2632       !AtomTy->isScalarType()) {
2633     // For GNU atomics, require a trivially-copyable type. This is not part of
2634     // the GNU atomics specification, but we enforce it for sanity.
2635     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2636       << Ptr->getType() << Ptr->getSourceRange();
2637     return ExprError();
2638   }
2639
2640   switch (ValType.getObjCLifetime()) {
2641   case Qualifiers::OCL_None:
2642   case Qualifiers::OCL_ExplicitNone:
2643     // okay
2644     break;
2645
2646   case Qualifiers::OCL_Weak:
2647   case Qualifiers::OCL_Strong:
2648   case Qualifiers::OCL_Autoreleasing:
2649     // FIXME: Can this happen? By this point, ValType should be known
2650     // to be trivially copyable.
2651     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2652       << ValType << Ptr->getSourceRange();
2653     return ExprError();
2654   }
2655
2656   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2657   // volatile-ness of the pointee-type inject itself into the result or the
2658   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2659   ValType.removeLocalVolatile();
2660   ValType.removeLocalConst();
2661   QualType ResultType = ValType;
2662   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2663     ResultType = Context.VoidTy;
2664   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2665     ResultType = Context.BoolTy;
2666
2667   // The type of a parameter passed 'by value'. In the GNU atomics, such
2668   // arguments are actually passed as pointers.
2669   QualType ByValType = ValType; // 'CP'
2670   if (!IsC11 && !IsN)
2671     ByValType = Ptr->getType();
2672
2673   // The first argument --- the pointer --- has a fixed type; we
2674   // deduce the types of the rest of the arguments accordingly.  Walk
2675   // the remaining arguments, converting them to the deduced value type.
2676   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2677     QualType Ty;
2678     if (i < NumVals[Form] + 1) {
2679       switch (i) {
2680       case 1:
2681         // The second argument is the non-atomic operand. For arithmetic, this
2682         // is always passed by value, and for a compare_exchange it is always
2683         // passed by address. For the rest, GNU uses by-address and C11 uses
2684         // by-value.
2685         assert(Form != Load);
2686         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2687           Ty = ValType;
2688         else if (Form == Copy || Form == Xchg)
2689           Ty = ByValType;
2690         else if (Form == Arithmetic)
2691           Ty = Context.getPointerDiffType();
2692         else {
2693           Expr *ValArg = TheCall->getArg(i);
2694           unsigned AS = 0;
2695           // Keep address space of non-atomic pointer type.
2696           if (const PointerType *PtrTy =
2697                   ValArg->getType()->getAs<PointerType>()) {
2698             AS = PtrTy->getPointeeType().getAddressSpace();
2699           }
2700           Ty = Context.getPointerType(
2701               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2702         }
2703         break;
2704       case 2:
2705         // The third argument to compare_exchange / GNU exchange is a
2706         // (pointer to a) desired value.
2707         Ty = ByValType;
2708         break;
2709       case 3:
2710         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2711         Ty = Context.BoolTy;
2712         break;
2713       }
2714     } else {
2715       // The order(s) are always converted to int.
2716       Ty = Context.IntTy;
2717     }
2718
2719     InitializedEntity Entity =
2720         InitializedEntity::InitializeParameter(Context, Ty, false);
2721     ExprResult Arg = TheCall->getArg(i);
2722     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2723     if (Arg.isInvalid())
2724       return true;
2725     TheCall->setArg(i, Arg.get());
2726   }
2727
2728   // Permute the arguments into a 'consistent' order.
2729   SmallVector<Expr*, 5> SubExprs;
2730   SubExprs.push_back(Ptr);
2731   switch (Form) {
2732   case Init:
2733     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2734     SubExprs.push_back(TheCall->getArg(1)); // Val1
2735     break;
2736   case Load:
2737     SubExprs.push_back(TheCall->getArg(1)); // Order
2738     break;
2739   case LoadCopy:
2740   case Copy:
2741   case Arithmetic:
2742   case Xchg:
2743     SubExprs.push_back(TheCall->getArg(2)); // Order
2744     SubExprs.push_back(TheCall->getArg(1)); // Val1
2745     break;
2746   case GNUXchg:
2747     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2748     SubExprs.push_back(TheCall->getArg(3)); // Order
2749     SubExprs.push_back(TheCall->getArg(1)); // Val1
2750     SubExprs.push_back(TheCall->getArg(2)); // Val2
2751     break;
2752   case C11CmpXchg:
2753     SubExprs.push_back(TheCall->getArg(3)); // Order
2754     SubExprs.push_back(TheCall->getArg(1)); // Val1
2755     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2756     SubExprs.push_back(TheCall->getArg(2)); // Val2
2757     break;
2758   case GNUCmpXchg:
2759     SubExprs.push_back(TheCall->getArg(4)); // Order
2760     SubExprs.push_back(TheCall->getArg(1)); // Val1
2761     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2762     SubExprs.push_back(TheCall->getArg(2)); // Val2
2763     SubExprs.push_back(TheCall->getArg(3)); // Weak
2764     break;
2765   }
2766
2767   if (SubExprs.size() >= 2 && Form != Init) {
2768     llvm::APSInt Result(32);
2769     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2770         !isValidOrderingForOp(Result.getSExtValue(), Op))
2771       Diag(SubExprs[1]->getLocStart(),
2772            diag::warn_atomic_op_has_invalid_memory_order)
2773           << SubExprs[1]->getSourceRange();
2774   }
2775
2776   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2777                                             SubExprs, ResultType, Op,
2778                                             TheCall->getRParenLoc());
2779   
2780   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2781        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2782       Context.AtomicUsesUnsupportedLibcall(AE))
2783     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2784     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2785
2786   return AE;
2787 }
2788
2789 /// checkBuiltinArgument - Given a call to a builtin function, perform
2790 /// normal type-checking on the given argument, updating the call in
2791 /// place.  This is useful when a builtin function requires custom
2792 /// type-checking for some of its arguments but not necessarily all of
2793 /// them.
2794 ///
2795 /// Returns true on error.
2796 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2797   FunctionDecl *Fn = E->getDirectCallee();
2798   assert(Fn && "builtin call without direct callee!");
2799
2800   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2801   InitializedEntity Entity =
2802     InitializedEntity::InitializeParameter(S.Context, Param);
2803
2804   ExprResult Arg = E->getArg(0);
2805   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2806   if (Arg.isInvalid())
2807     return true;
2808
2809   E->setArg(ArgIndex, Arg.get());
2810   return false;
2811 }
2812
2813 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2814 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2815 /// type of its first argument.  The main ActOnCallExpr routines have already
2816 /// promoted the types of arguments because all of these calls are prototyped as
2817 /// void(...).
2818 ///
2819 /// This function goes through and does final semantic checking for these
2820 /// builtins,
2821 ExprResult
2822 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2823   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2824   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2825   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2826
2827   // Ensure that we have at least one argument to do type inference from.
2828   if (TheCall->getNumArgs() < 1) {
2829     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2830       << 0 << 1 << TheCall->getNumArgs()
2831       << TheCall->getCallee()->getSourceRange();
2832     return ExprError();
2833   }
2834
2835   // Inspect the first argument of the atomic builtin.  This should always be
2836   // a pointer type, whose element is an integral scalar or pointer type.
2837   // Because it is a pointer type, we don't have to worry about any implicit
2838   // casts here.
2839   // FIXME: We don't allow floating point scalars as input.
2840   Expr *FirstArg = TheCall->getArg(0);
2841   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2842   if (FirstArgResult.isInvalid())
2843     return ExprError();
2844   FirstArg = FirstArgResult.get();
2845   TheCall->setArg(0, FirstArg);
2846
2847   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2848   if (!pointerType) {
2849     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2850       << FirstArg->getType() << FirstArg->getSourceRange();
2851     return ExprError();
2852   }
2853
2854   QualType ValType = pointerType->getPointeeType();
2855   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2856       !ValType->isBlockPointerType()) {
2857     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2858       << FirstArg->getType() << FirstArg->getSourceRange();
2859     return ExprError();
2860   }
2861
2862   switch (ValType.getObjCLifetime()) {
2863   case Qualifiers::OCL_None:
2864   case Qualifiers::OCL_ExplicitNone:
2865     // okay
2866     break;
2867
2868   case Qualifiers::OCL_Weak:
2869   case Qualifiers::OCL_Strong:
2870   case Qualifiers::OCL_Autoreleasing:
2871     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2872       << ValType << FirstArg->getSourceRange();
2873     return ExprError();
2874   }
2875
2876   // Strip any qualifiers off ValType.
2877   ValType = ValType.getUnqualifiedType();
2878
2879   // The majority of builtins return a value, but a few have special return
2880   // types, so allow them to override appropriately below.
2881   QualType ResultType = ValType;
2882
2883   // We need to figure out which concrete builtin this maps onto.  For example,
2884   // __sync_fetch_and_add with a 2 byte object turns into
2885   // __sync_fetch_and_add_2.
2886 #define BUILTIN_ROW(x) \
2887   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2888     Builtin::BI##x##_8, Builtin::BI##x##_16 }
2889
2890   static const unsigned BuiltinIndices[][5] = {
2891     BUILTIN_ROW(__sync_fetch_and_add),
2892     BUILTIN_ROW(__sync_fetch_and_sub),
2893     BUILTIN_ROW(__sync_fetch_and_or),
2894     BUILTIN_ROW(__sync_fetch_and_and),
2895     BUILTIN_ROW(__sync_fetch_and_xor),
2896     BUILTIN_ROW(__sync_fetch_and_nand),
2897
2898     BUILTIN_ROW(__sync_add_and_fetch),
2899     BUILTIN_ROW(__sync_sub_and_fetch),
2900     BUILTIN_ROW(__sync_and_and_fetch),
2901     BUILTIN_ROW(__sync_or_and_fetch),
2902     BUILTIN_ROW(__sync_xor_and_fetch),
2903     BUILTIN_ROW(__sync_nand_and_fetch),
2904
2905     BUILTIN_ROW(__sync_val_compare_and_swap),
2906     BUILTIN_ROW(__sync_bool_compare_and_swap),
2907     BUILTIN_ROW(__sync_lock_test_and_set),
2908     BUILTIN_ROW(__sync_lock_release),
2909     BUILTIN_ROW(__sync_swap)
2910   };
2911 #undef BUILTIN_ROW
2912
2913   // Determine the index of the size.
2914   unsigned SizeIndex;
2915   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2916   case 1: SizeIndex = 0; break;
2917   case 2: SizeIndex = 1; break;
2918   case 4: SizeIndex = 2; break;
2919   case 8: SizeIndex = 3; break;
2920   case 16: SizeIndex = 4; break;
2921   default:
2922     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2923       << FirstArg->getType() << FirstArg->getSourceRange();
2924     return ExprError();
2925   }
2926
2927   // Each of these builtins has one pointer argument, followed by some number of
2928   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2929   // that we ignore.  Find out which row of BuiltinIndices to read from as well
2930   // as the number of fixed args.
2931   unsigned BuiltinID = FDecl->getBuiltinID();
2932   unsigned BuiltinIndex, NumFixed = 1;
2933   bool WarnAboutSemanticsChange = false;
2934   switch (BuiltinID) {
2935   default: llvm_unreachable("Unknown overloaded atomic builtin!");
2936   case Builtin::BI__sync_fetch_and_add: 
2937   case Builtin::BI__sync_fetch_and_add_1:
2938   case Builtin::BI__sync_fetch_and_add_2:
2939   case Builtin::BI__sync_fetch_and_add_4:
2940   case Builtin::BI__sync_fetch_and_add_8:
2941   case Builtin::BI__sync_fetch_and_add_16:
2942     BuiltinIndex = 0; 
2943     break;
2944       
2945   case Builtin::BI__sync_fetch_and_sub: 
2946   case Builtin::BI__sync_fetch_and_sub_1:
2947   case Builtin::BI__sync_fetch_and_sub_2:
2948   case Builtin::BI__sync_fetch_and_sub_4:
2949   case Builtin::BI__sync_fetch_and_sub_8:
2950   case Builtin::BI__sync_fetch_and_sub_16:
2951     BuiltinIndex = 1; 
2952     break;
2953       
2954   case Builtin::BI__sync_fetch_and_or:  
2955   case Builtin::BI__sync_fetch_and_or_1:
2956   case Builtin::BI__sync_fetch_and_or_2:
2957   case Builtin::BI__sync_fetch_and_or_4:
2958   case Builtin::BI__sync_fetch_and_or_8:
2959   case Builtin::BI__sync_fetch_and_or_16:
2960     BuiltinIndex = 2; 
2961     break;
2962       
2963   case Builtin::BI__sync_fetch_and_and: 
2964   case Builtin::BI__sync_fetch_and_and_1:
2965   case Builtin::BI__sync_fetch_and_and_2:
2966   case Builtin::BI__sync_fetch_and_and_4:
2967   case Builtin::BI__sync_fetch_and_and_8:
2968   case Builtin::BI__sync_fetch_and_and_16:
2969     BuiltinIndex = 3; 
2970     break;
2971
2972   case Builtin::BI__sync_fetch_and_xor: 
2973   case Builtin::BI__sync_fetch_and_xor_1:
2974   case Builtin::BI__sync_fetch_and_xor_2:
2975   case Builtin::BI__sync_fetch_and_xor_4:
2976   case Builtin::BI__sync_fetch_and_xor_8:
2977   case Builtin::BI__sync_fetch_and_xor_16:
2978     BuiltinIndex = 4; 
2979     break;
2980
2981   case Builtin::BI__sync_fetch_and_nand: 
2982   case Builtin::BI__sync_fetch_and_nand_1:
2983   case Builtin::BI__sync_fetch_and_nand_2:
2984   case Builtin::BI__sync_fetch_and_nand_4:
2985   case Builtin::BI__sync_fetch_and_nand_8:
2986   case Builtin::BI__sync_fetch_and_nand_16:
2987     BuiltinIndex = 5;
2988     WarnAboutSemanticsChange = true;
2989     break;
2990
2991   case Builtin::BI__sync_add_and_fetch: 
2992   case Builtin::BI__sync_add_and_fetch_1:
2993   case Builtin::BI__sync_add_and_fetch_2:
2994   case Builtin::BI__sync_add_and_fetch_4:
2995   case Builtin::BI__sync_add_and_fetch_8:
2996   case Builtin::BI__sync_add_and_fetch_16:
2997     BuiltinIndex = 6; 
2998     break;
2999       
3000   case Builtin::BI__sync_sub_and_fetch: 
3001   case Builtin::BI__sync_sub_and_fetch_1:
3002   case Builtin::BI__sync_sub_and_fetch_2:
3003   case Builtin::BI__sync_sub_and_fetch_4:
3004   case Builtin::BI__sync_sub_and_fetch_8:
3005   case Builtin::BI__sync_sub_and_fetch_16:
3006     BuiltinIndex = 7; 
3007     break;
3008       
3009   case Builtin::BI__sync_and_and_fetch: 
3010   case Builtin::BI__sync_and_and_fetch_1:
3011   case Builtin::BI__sync_and_and_fetch_2:
3012   case Builtin::BI__sync_and_and_fetch_4:
3013   case Builtin::BI__sync_and_and_fetch_8:
3014   case Builtin::BI__sync_and_and_fetch_16:
3015     BuiltinIndex = 8; 
3016     break;
3017       
3018   case Builtin::BI__sync_or_and_fetch:  
3019   case Builtin::BI__sync_or_and_fetch_1:
3020   case Builtin::BI__sync_or_and_fetch_2:
3021   case Builtin::BI__sync_or_and_fetch_4:
3022   case Builtin::BI__sync_or_and_fetch_8:
3023   case Builtin::BI__sync_or_and_fetch_16:
3024     BuiltinIndex = 9; 
3025     break;
3026       
3027   case Builtin::BI__sync_xor_and_fetch: 
3028   case Builtin::BI__sync_xor_and_fetch_1:
3029   case Builtin::BI__sync_xor_and_fetch_2:
3030   case Builtin::BI__sync_xor_and_fetch_4:
3031   case Builtin::BI__sync_xor_and_fetch_8:
3032   case Builtin::BI__sync_xor_and_fetch_16:
3033     BuiltinIndex = 10;
3034     break;
3035
3036   case Builtin::BI__sync_nand_and_fetch: 
3037   case Builtin::BI__sync_nand_and_fetch_1:
3038   case Builtin::BI__sync_nand_and_fetch_2:
3039   case Builtin::BI__sync_nand_and_fetch_4:
3040   case Builtin::BI__sync_nand_and_fetch_8:
3041   case Builtin::BI__sync_nand_and_fetch_16:
3042     BuiltinIndex = 11;
3043     WarnAboutSemanticsChange = true;
3044     break;
3045
3046   case Builtin::BI__sync_val_compare_and_swap:
3047   case Builtin::BI__sync_val_compare_and_swap_1:
3048   case Builtin::BI__sync_val_compare_and_swap_2:
3049   case Builtin::BI__sync_val_compare_and_swap_4:
3050   case Builtin::BI__sync_val_compare_and_swap_8:
3051   case Builtin::BI__sync_val_compare_and_swap_16:
3052     BuiltinIndex = 12;
3053     NumFixed = 2;
3054     break;
3055       
3056   case Builtin::BI__sync_bool_compare_and_swap:
3057   case Builtin::BI__sync_bool_compare_and_swap_1:
3058   case Builtin::BI__sync_bool_compare_and_swap_2:
3059   case Builtin::BI__sync_bool_compare_and_swap_4:
3060   case Builtin::BI__sync_bool_compare_and_swap_8:
3061   case Builtin::BI__sync_bool_compare_and_swap_16:
3062     BuiltinIndex = 13;
3063     NumFixed = 2;
3064     ResultType = Context.BoolTy;
3065     break;
3066       
3067   case Builtin::BI__sync_lock_test_and_set: 
3068   case Builtin::BI__sync_lock_test_and_set_1:
3069   case Builtin::BI__sync_lock_test_and_set_2:
3070   case Builtin::BI__sync_lock_test_and_set_4:
3071   case Builtin::BI__sync_lock_test_and_set_8:
3072   case Builtin::BI__sync_lock_test_and_set_16:
3073     BuiltinIndex = 14; 
3074     break;
3075       
3076   case Builtin::BI__sync_lock_release:
3077   case Builtin::BI__sync_lock_release_1:
3078   case Builtin::BI__sync_lock_release_2:
3079   case Builtin::BI__sync_lock_release_4:
3080   case Builtin::BI__sync_lock_release_8:
3081   case Builtin::BI__sync_lock_release_16:
3082     BuiltinIndex = 15;
3083     NumFixed = 0;
3084     ResultType = Context.VoidTy;
3085     break;
3086       
3087   case Builtin::BI__sync_swap: 
3088   case Builtin::BI__sync_swap_1:
3089   case Builtin::BI__sync_swap_2:
3090   case Builtin::BI__sync_swap_4:
3091   case Builtin::BI__sync_swap_8:
3092   case Builtin::BI__sync_swap_16:
3093     BuiltinIndex = 16; 
3094     break;
3095   }
3096
3097   // Now that we know how many fixed arguments we expect, first check that we
3098   // have at least that many.
3099   if (TheCall->getNumArgs() < 1+NumFixed) {
3100     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3101       << 0 << 1+NumFixed << TheCall->getNumArgs()
3102       << TheCall->getCallee()->getSourceRange();
3103     return ExprError();
3104   }
3105
3106   if (WarnAboutSemanticsChange) {
3107     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3108       << TheCall->getCallee()->getSourceRange();
3109   }
3110
3111   // Get the decl for the concrete builtin from this, we can tell what the
3112   // concrete integer type we should convert to is.
3113   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3114   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3115   FunctionDecl *NewBuiltinDecl;
3116   if (NewBuiltinID == BuiltinID)
3117     NewBuiltinDecl = FDecl;
3118   else {
3119     // Perform builtin lookup to avoid redeclaring it.
3120     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3121     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3122     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3123     assert(Res.getFoundDecl());
3124     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3125     if (!NewBuiltinDecl)
3126       return ExprError();
3127   }
3128
3129   // The first argument --- the pointer --- has a fixed type; we
3130   // deduce the types of the rest of the arguments accordingly.  Walk
3131   // the remaining arguments, converting them to the deduced value type.
3132   for (unsigned i = 0; i != NumFixed; ++i) {
3133     ExprResult Arg = TheCall->getArg(i+1);
3134
3135     // GCC does an implicit conversion to the pointer or integer ValType.  This
3136     // can fail in some cases (1i -> int**), check for this error case now.
3137     // Initialize the argument.
3138     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3139                                                    ValType, /*consume*/ false);
3140     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3141     if (Arg.isInvalid())
3142       return ExprError();
3143
3144     // Okay, we have something that *can* be converted to the right type.  Check
3145     // to see if there is a potentially weird extension going on here.  This can
3146     // happen when you do an atomic operation on something like an char* and
3147     // pass in 42.  The 42 gets converted to char.  This is even more strange
3148     // for things like 45.123 -> char, etc.
3149     // FIXME: Do this check.
3150     TheCall->setArg(i+1, Arg.get());
3151   }
3152
3153   ASTContext& Context = this->getASTContext();
3154
3155   // Create a new DeclRefExpr to refer to the new decl.
3156   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3157       Context,
3158       DRE->getQualifierLoc(),
3159       SourceLocation(),
3160       NewBuiltinDecl,
3161       /*enclosing*/ false,
3162       DRE->getLocation(),
3163       Context.BuiltinFnTy,
3164       DRE->getValueKind());
3165
3166   // Set the callee in the CallExpr.
3167   // FIXME: This loses syntactic information.
3168   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3169   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3170                                               CK_BuiltinFnToFnPtr);
3171   TheCall->setCallee(PromotedCall.get());
3172
3173   // Change the result type of the call to match the original value type. This
3174   // is arbitrary, but the codegen for these builtins ins design to handle it
3175   // gracefully.
3176   TheCall->setType(ResultType);
3177
3178   return TheCallResult;
3179 }
3180
3181 /// SemaBuiltinNontemporalOverloaded - We have a call to
3182 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3183 /// overloaded function based on the pointer type of its last argument.
3184 ///
3185 /// This function goes through and does final semantic checking for these
3186 /// builtins.
3187 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3188   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3189   DeclRefExpr *DRE =
3190       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3191   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3192   unsigned BuiltinID = FDecl->getBuiltinID();
3193   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3194           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3195          "Unexpected nontemporal load/store builtin!");
3196   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3197   unsigned numArgs = isStore ? 2 : 1;
3198
3199   // Ensure that we have the proper number of arguments.
3200   if (checkArgCount(*this, TheCall, numArgs))
3201     return ExprError();
3202
3203   // Inspect the last argument of the nontemporal builtin.  This should always
3204   // be a pointer type, from which we imply the type of the memory access.
3205   // Because it is a pointer type, we don't have to worry about any implicit
3206   // casts here.
3207   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3208   ExprResult PointerArgResult =
3209       DefaultFunctionArrayLvalueConversion(PointerArg);
3210
3211   if (PointerArgResult.isInvalid())
3212     return ExprError();
3213   PointerArg = PointerArgResult.get();
3214   TheCall->setArg(numArgs - 1, PointerArg);
3215
3216   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3217   if (!pointerType) {
3218     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3219         << PointerArg->getType() << PointerArg->getSourceRange();
3220     return ExprError();
3221   }
3222
3223   QualType ValType = pointerType->getPointeeType();
3224
3225   // Strip any qualifiers off ValType.
3226   ValType = ValType.getUnqualifiedType();
3227   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3228       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3229       !ValType->isVectorType()) {
3230     Diag(DRE->getLocStart(),
3231          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3232         << PointerArg->getType() << PointerArg->getSourceRange();
3233     return ExprError();
3234   }
3235
3236   if (!isStore) {
3237     TheCall->setType(ValType);
3238     return TheCallResult;
3239   }
3240
3241   ExprResult ValArg = TheCall->getArg(0);
3242   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3243       Context, ValType, /*consume*/ false);
3244   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3245   if (ValArg.isInvalid())
3246     return ExprError();
3247
3248   TheCall->setArg(0, ValArg.get());
3249   TheCall->setType(Context.VoidTy);
3250   return TheCallResult;
3251 }
3252
3253 /// CheckObjCString - Checks that the argument to the builtin
3254 /// CFString constructor is correct
3255 /// Note: It might also make sense to do the UTF-16 conversion here (would
3256 /// simplify the backend).
3257 bool Sema::CheckObjCString(Expr *Arg) {
3258   Arg = Arg->IgnoreParenCasts();
3259   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3260
3261   if (!Literal || !Literal->isAscii()) {
3262     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3263       << Arg->getSourceRange();
3264     return true;
3265   }
3266
3267   if (Literal->containsNonAsciiOrNull()) {
3268     StringRef String = Literal->getString();
3269     unsigned NumBytes = String.size();
3270     SmallVector<UTF16, 128> ToBuf(NumBytes);
3271     const UTF8 *FromPtr = (const UTF8 *)String.data();
3272     UTF16 *ToPtr = &ToBuf[0];
3273     
3274     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3275                                                  &ToPtr, ToPtr + NumBytes,
3276                                                  strictConversion);
3277     // Check for conversion failure.
3278     if (Result != conversionOK)
3279       Diag(Arg->getLocStart(),
3280            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3281   }
3282   return false;
3283 }
3284
3285 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3286 /// for validity.  Emit an error and return true on failure; return false
3287 /// on success.
3288 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3289   Expr *Fn = TheCall->getCallee();
3290   if (TheCall->getNumArgs() > 2) {
3291     Diag(TheCall->getArg(2)->getLocStart(),
3292          diag::err_typecheck_call_too_many_args)
3293       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3294       << Fn->getSourceRange()
3295       << SourceRange(TheCall->getArg(2)->getLocStart(),
3296                      (*(TheCall->arg_end()-1))->getLocEnd());
3297     return true;
3298   }
3299
3300   if (TheCall->getNumArgs() < 2) {
3301     return Diag(TheCall->getLocEnd(),
3302       diag::err_typecheck_call_too_few_args_at_least)
3303       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3304   }
3305
3306   // Type-check the first argument normally.
3307   if (checkBuiltinArgument(*this, TheCall, 0))
3308     return true;
3309
3310   // Determine whether the current function is variadic or not.
3311   BlockScopeInfo *CurBlock = getCurBlock();
3312   bool isVariadic;
3313   if (CurBlock)
3314     isVariadic = CurBlock->TheDecl->isVariadic();
3315   else if (FunctionDecl *FD = getCurFunctionDecl())
3316     isVariadic = FD->isVariadic();
3317   else
3318     isVariadic = getCurMethodDecl()->isVariadic();
3319
3320   if (!isVariadic) {
3321     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3322     return true;
3323   }
3324
3325   // Verify that the second argument to the builtin is the last argument of the
3326   // current function or method.
3327   bool SecondArgIsLastNamedArgument = false;
3328   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3329
3330   // These are valid if SecondArgIsLastNamedArgument is false after the next
3331   // block.
3332   QualType Type;
3333   SourceLocation ParamLoc;
3334   bool IsCRegister = false;
3335
3336   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3337     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3338       // FIXME: This isn't correct for methods (results in bogus warning).
3339       // Get the last formal in the current function.
3340       const ParmVarDecl *LastArg;
3341       if (CurBlock)
3342         LastArg = CurBlock->TheDecl->parameters().back();
3343       else if (FunctionDecl *FD = getCurFunctionDecl())
3344         LastArg = FD->parameters().back();
3345       else
3346         LastArg = getCurMethodDecl()->parameters().back();
3347       SecondArgIsLastNamedArgument = PV == LastArg;
3348
3349       Type = PV->getType();
3350       ParamLoc = PV->getLocation();
3351       IsCRegister =
3352           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3353     }
3354   }
3355
3356   if (!SecondArgIsLastNamedArgument)
3357     Diag(TheCall->getArg(1)->getLocStart(),
3358          diag::warn_second_arg_of_va_start_not_last_named_param);
3359   else if (IsCRegister || Type->isReferenceType() ||
3360            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3361              // Promotable integers are UB, but enumerations need a bit of
3362              // extra checking to see what their promotable type actually is.
3363              if (!Type->isPromotableIntegerType())
3364                return false;
3365              if (!Type->isEnumeralType())
3366                return true;
3367              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3368              return !(ED &&
3369                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3370            }()) {
3371     unsigned Reason = 0;
3372     if (Type->isReferenceType())  Reason = 1;
3373     else if (IsCRegister)         Reason = 2;
3374     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3375     Diag(ParamLoc, diag::note_parameter_type) << Type;
3376   }
3377
3378   TheCall->setType(Context.VoidTy);
3379   return false;
3380 }
3381
3382 /// Check the arguments to '__builtin_va_start' for validity, and that
3383 /// it was called from a function of the native ABI.
3384 /// Emit an error and return true on failure; return false on success.
3385 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3386   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3387   // On x64 Windows, don't allow this in System V ABI functions.
3388   // (Yes, that means there's no corresponding way to support variadic
3389   // System V ABI functions on Windows.)
3390   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3391     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3392     clang::CallingConv CC = CC_C;
3393     if (const FunctionDecl *FD = getCurFunctionDecl())
3394       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3395     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3396         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3397       return Diag(TheCall->getCallee()->getLocStart(),
3398                   diag::err_va_start_used_in_wrong_abi_function)
3399              << (OS != llvm::Triple::Win32);
3400   }
3401   return SemaBuiltinVAStartImpl(TheCall);
3402 }
3403
3404 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3405 /// it was called from a Win64 ABI function.
3406 /// Emit an error and return true on failure; return false on success.
3407 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3408   // This only makes sense for x86-64.
3409   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3410   Expr *Callee = TheCall->getCallee();
3411   if (TT.getArch() != llvm::Triple::x86_64)
3412     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3413   // Don't allow this in System V ABI functions.
3414   clang::CallingConv CC = CC_C;
3415   if (const FunctionDecl *FD = getCurFunctionDecl())
3416     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3417   if (CC == CC_X86_64SysV ||
3418       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3419     return Diag(Callee->getLocStart(),
3420                 diag::err_ms_va_start_used_in_sysv_function);
3421   return SemaBuiltinVAStartImpl(TheCall);
3422 }
3423
3424 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3425   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3426   //                 const char *named_addr);
3427
3428   Expr *Func = Call->getCallee();
3429
3430   if (Call->getNumArgs() < 3)
3431     return Diag(Call->getLocEnd(),
3432                 diag::err_typecheck_call_too_few_args_at_least)
3433            << 0 /*function call*/ << 3 << Call->getNumArgs();
3434
3435   // Determine whether the current function is variadic or not.
3436   bool IsVariadic;
3437   if (BlockScopeInfo *CurBlock = getCurBlock())
3438     IsVariadic = CurBlock->TheDecl->isVariadic();
3439   else if (FunctionDecl *FD = getCurFunctionDecl())
3440     IsVariadic = FD->isVariadic();
3441   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3442     IsVariadic = MD->isVariadic();
3443   else
3444     llvm_unreachable("unexpected statement type");
3445
3446   if (!IsVariadic) {
3447     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3448     return true;
3449   }
3450
3451   // Type-check the first argument normally.
3452   if (checkBuiltinArgument(*this, Call, 0))
3453     return true;
3454
3455   const struct {
3456     unsigned ArgNo;
3457     QualType Type;
3458   } ArgumentTypes[] = {
3459     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3460     { 2, Context.getSizeType() },
3461   };
3462
3463   for (const auto &AT : ArgumentTypes) {
3464     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3465     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3466       continue;
3467     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3468       << Arg->getType() << AT.Type << 1 /* different class */
3469       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3470       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3471   }
3472
3473   return false;
3474 }
3475
3476 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3477 /// friends.  This is declared to take (...), so we have to check everything.
3478 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3479   if (TheCall->getNumArgs() < 2)
3480     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3481       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3482   if (TheCall->getNumArgs() > 2)
3483     return Diag(TheCall->getArg(2)->getLocStart(),
3484                 diag::err_typecheck_call_too_many_args)
3485       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3486       << SourceRange(TheCall->getArg(2)->getLocStart(),
3487                      (*(TheCall->arg_end()-1))->getLocEnd());
3488
3489   ExprResult OrigArg0 = TheCall->getArg(0);
3490   ExprResult OrigArg1 = TheCall->getArg(1);
3491
3492   // Do standard promotions between the two arguments, returning their common
3493   // type.
3494   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3495   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3496     return true;
3497
3498   // Make sure any conversions are pushed back into the call; this is
3499   // type safe since unordered compare builtins are declared as "_Bool
3500   // foo(...)".
3501   TheCall->setArg(0, OrigArg0.get());
3502   TheCall->setArg(1, OrigArg1.get());
3503
3504   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3505     return false;
3506
3507   // If the common type isn't a real floating type, then the arguments were
3508   // invalid for this operation.
3509   if (Res.isNull() || !Res->isRealFloatingType())
3510     return Diag(OrigArg0.get()->getLocStart(),
3511                 diag::err_typecheck_call_invalid_ordered_compare)
3512       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3513       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3514
3515   return false;
3516 }
3517
3518 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3519 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3520 /// to check everything. We expect the last argument to be a floating point
3521 /// value.
3522 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3523   if (TheCall->getNumArgs() < NumArgs)
3524     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3525       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3526   if (TheCall->getNumArgs() > NumArgs)
3527     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3528                 diag::err_typecheck_call_too_many_args)
3529       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3530       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3531                      (*(TheCall->arg_end()-1))->getLocEnd());
3532
3533   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3534
3535   if (OrigArg->isTypeDependent())
3536     return false;
3537
3538   // This operation requires a non-_Complex floating-point number.
3539   if (!OrigArg->getType()->isRealFloatingType())
3540     return Diag(OrigArg->getLocStart(),
3541                 diag::err_typecheck_call_invalid_unary_fp)
3542       << OrigArg->getType() << OrigArg->getSourceRange();
3543
3544   // If this is an implicit conversion from float -> double, remove it.
3545   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3546     Expr *CastArg = Cast->getSubExpr();
3547     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3548       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3549              "promotion from float to double is the only expected cast here");
3550       Cast->setSubExpr(nullptr);
3551       TheCall->setArg(NumArgs-1, CastArg);
3552     }
3553   }
3554   
3555   return false;
3556 }
3557
3558 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3559 // This is declared to take (...), so we have to check everything.
3560 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3561   if (TheCall->getNumArgs() < 2)
3562     return ExprError(Diag(TheCall->getLocEnd(),
3563                           diag::err_typecheck_call_too_few_args_at_least)
3564                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3565                      << TheCall->getSourceRange());
3566
3567   // Determine which of the following types of shufflevector we're checking:
3568   // 1) unary, vector mask: (lhs, mask)
3569   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3570   QualType resType = TheCall->getArg(0)->getType();
3571   unsigned numElements = 0;
3572
3573   if (!TheCall->getArg(0)->isTypeDependent() &&
3574       !TheCall->getArg(1)->isTypeDependent()) {
3575     QualType LHSType = TheCall->getArg(0)->getType();
3576     QualType RHSType = TheCall->getArg(1)->getType();
3577
3578     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3579       return ExprError(Diag(TheCall->getLocStart(),
3580                             diag::err_shufflevector_non_vector)
3581                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3582                                       TheCall->getArg(1)->getLocEnd()));
3583
3584     numElements = LHSType->getAs<VectorType>()->getNumElements();
3585     unsigned numResElements = TheCall->getNumArgs() - 2;
3586
3587     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3588     // with mask.  If so, verify that RHS is an integer vector type with the
3589     // same number of elts as lhs.
3590     if (TheCall->getNumArgs() == 2) {
3591       if (!RHSType->hasIntegerRepresentation() ||
3592           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3593         return ExprError(Diag(TheCall->getLocStart(),
3594                               diag::err_shufflevector_incompatible_vector)
3595                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3596                                         TheCall->getArg(1)->getLocEnd()));
3597     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3598       return ExprError(Diag(TheCall->getLocStart(),
3599                             diag::err_shufflevector_incompatible_vector)
3600                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3601                                       TheCall->getArg(1)->getLocEnd()));
3602     } else if (numElements != numResElements) {
3603       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3604       resType = Context.getVectorType(eltType, numResElements,
3605                                       VectorType::GenericVector);
3606     }
3607   }
3608
3609   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3610     if (TheCall->getArg(i)->isTypeDependent() ||
3611         TheCall->getArg(i)->isValueDependent())
3612       continue;
3613
3614     llvm::APSInt Result(32);
3615     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3616       return ExprError(Diag(TheCall->getLocStart(),
3617                             diag::err_shufflevector_nonconstant_argument)
3618                        << TheCall->getArg(i)->getSourceRange());
3619
3620     // Allow -1 which will be translated to undef in the IR.
3621     if (Result.isSigned() && Result.isAllOnesValue())
3622       continue;
3623
3624     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3625       return ExprError(Diag(TheCall->getLocStart(),
3626                             diag::err_shufflevector_argument_too_large)
3627                        << TheCall->getArg(i)->getSourceRange());
3628   }
3629
3630   SmallVector<Expr*, 32> exprs;
3631
3632   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3633     exprs.push_back(TheCall->getArg(i));
3634     TheCall->setArg(i, nullptr);
3635   }
3636
3637   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3638                                          TheCall->getCallee()->getLocStart(),
3639                                          TheCall->getRParenLoc());
3640 }
3641
3642 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3643 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3644                                        SourceLocation BuiltinLoc,
3645                                        SourceLocation RParenLoc) {
3646   ExprValueKind VK = VK_RValue;
3647   ExprObjectKind OK = OK_Ordinary;
3648   QualType DstTy = TInfo->getType();
3649   QualType SrcTy = E->getType();
3650
3651   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3652     return ExprError(Diag(BuiltinLoc,
3653                           diag::err_convertvector_non_vector)
3654                      << E->getSourceRange());
3655   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3656     return ExprError(Diag(BuiltinLoc,
3657                           diag::err_convertvector_non_vector_type));
3658
3659   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3660     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3661     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3662     if (SrcElts != DstElts)
3663       return ExprError(Diag(BuiltinLoc,
3664                             diag::err_convertvector_incompatible_vector)
3665                        << E->getSourceRange());
3666   }
3667
3668   return new (Context)
3669       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3670 }
3671
3672 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3673 // This is declared to take (const void*, ...) and can take two
3674 // optional constant int args.
3675 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3676   unsigned NumArgs = TheCall->getNumArgs();
3677
3678   if (NumArgs > 3)
3679     return Diag(TheCall->getLocEnd(),
3680              diag::err_typecheck_call_too_many_args_at_most)
3681              << 0 /*function call*/ << 3 << NumArgs
3682              << TheCall->getSourceRange();
3683
3684   // Argument 0 is checked for us and the remaining arguments must be
3685   // constant integers.
3686   for (unsigned i = 1; i != NumArgs; ++i)
3687     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3688       return true;
3689
3690   return false;
3691 }
3692
3693 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3694 // __assume does not evaluate its arguments, and should warn if its argument
3695 // has side effects.
3696 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3697   Expr *Arg = TheCall->getArg(0);
3698   if (Arg->isInstantiationDependent()) return false;
3699
3700   if (Arg->HasSideEffects(Context))
3701     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3702       << Arg->getSourceRange()
3703       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3704
3705   return false;
3706 }
3707
3708 /// Handle __builtin_assume_aligned. This is declared
3709 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3710 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3711   unsigned NumArgs = TheCall->getNumArgs();
3712
3713   if (NumArgs > 3)
3714     return Diag(TheCall->getLocEnd(),
3715              diag::err_typecheck_call_too_many_args_at_most)
3716              << 0 /*function call*/ << 3 << NumArgs
3717              << TheCall->getSourceRange();
3718
3719   // The alignment must be a constant integer.
3720   Expr *Arg = TheCall->getArg(1);
3721
3722   // We can't check the value of a dependent argument.
3723   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3724     llvm::APSInt Result;
3725     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3726       return true;
3727
3728     if (!Result.isPowerOf2())
3729       return Diag(TheCall->getLocStart(),
3730                   diag::err_alignment_not_power_of_two)
3731            << Arg->getSourceRange();
3732   }
3733
3734   if (NumArgs > 2) {
3735     ExprResult Arg(TheCall->getArg(2));
3736     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3737       Context.getSizeType(), false);
3738     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3739     if (Arg.isInvalid()) return true;
3740     TheCall->setArg(2, Arg.get());
3741   }
3742
3743   return false;
3744 }
3745
3746 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3747 /// TheCall is a constant expression.
3748 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3749                                   llvm::APSInt &Result) {
3750   Expr *Arg = TheCall->getArg(ArgNum);
3751   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3752   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3753   
3754   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3755   
3756   if (!Arg->isIntegerConstantExpr(Result, Context))
3757     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3758                 << FDecl->getDeclName() <<  Arg->getSourceRange();
3759   
3760   return false;
3761 }
3762
3763 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3764 /// TheCall is a constant expression in the range [Low, High].
3765 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3766                                        int Low, int High) {
3767   llvm::APSInt Result;
3768
3769   // We can't check the value of a dependent argument.
3770   Expr *Arg = TheCall->getArg(ArgNum);
3771   if (Arg->isTypeDependent() || Arg->isValueDependent())
3772     return false;
3773
3774   // Check constant-ness first.
3775   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3776     return true;
3777
3778   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3779     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3780       << Low << High << Arg->getSourceRange();
3781
3782   return false;
3783 }
3784
3785 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
3786 /// TheCall is a constant expression is a multiple of Num..
3787 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
3788                                           unsigned Num) {
3789   llvm::APSInt Result;
3790
3791   // We can't check the value of a dependent argument.
3792   Expr *Arg = TheCall->getArg(ArgNum);
3793   if (Arg->isTypeDependent() || Arg->isValueDependent())
3794     return false;
3795
3796   // Check constant-ness first.
3797   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3798     return true;
3799
3800   if (Result.getSExtValue() % Num != 0)
3801     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
3802       << Num << Arg->getSourceRange();
3803
3804   return false;
3805 }
3806
3807 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3808 /// TheCall is an ARM/AArch64 special register string literal.
3809 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3810                                     int ArgNum, unsigned ExpectedFieldNum,
3811                                     bool AllowName) {
3812   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3813                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3814                       BuiltinID == ARM::BI__builtin_arm_rsr ||
3815                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3816                       BuiltinID == ARM::BI__builtin_arm_wsr ||
3817                       BuiltinID == ARM::BI__builtin_arm_wsrp;
3818   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3819                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3820                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
3821                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3822                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
3823                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
3824   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3825
3826   // We can't check the value of a dependent argument.
3827   Expr *Arg = TheCall->getArg(ArgNum);
3828   if (Arg->isTypeDependent() || Arg->isValueDependent())
3829     return false;
3830
3831   // Check if the argument is a string literal.
3832   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3833     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3834            << Arg->getSourceRange();
3835
3836   // Check the type of special register given.
3837   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3838   SmallVector<StringRef, 6> Fields;
3839   Reg.split(Fields, ":");
3840
3841   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3842     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3843            << Arg->getSourceRange();
3844
3845   // If the string is the name of a register then we cannot check that it is
3846   // valid here but if the string is of one the forms described in ACLE then we
3847   // can check that the supplied fields are integers and within the valid
3848   // ranges.
3849   if (Fields.size() > 1) {
3850     bool FiveFields = Fields.size() == 5;
3851
3852     bool ValidString = true;
3853     if (IsARMBuiltin) {
3854       ValidString &= Fields[0].startswith_lower("cp") ||
3855                      Fields[0].startswith_lower("p");
3856       if (ValidString)
3857         Fields[0] =
3858           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3859
3860       ValidString &= Fields[2].startswith_lower("c");
3861       if (ValidString)
3862         Fields[2] = Fields[2].drop_front(1);
3863
3864       if (FiveFields) {
3865         ValidString &= Fields[3].startswith_lower("c");
3866         if (ValidString)
3867           Fields[3] = Fields[3].drop_front(1);
3868       }
3869     }
3870
3871     SmallVector<int, 5> Ranges;
3872     if (FiveFields)
3873       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3874     else
3875       Ranges.append({15, 7, 15});
3876
3877     for (unsigned i=0; i<Fields.size(); ++i) {
3878       int IntField;
3879       ValidString &= !Fields[i].getAsInteger(10, IntField);
3880       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3881     }
3882
3883     if (!ValidString)
3884       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3885              << Arg->getSourceRange();
3886
3887   } else if (IsAArch64Builtin && Fields.size() == 1) {
3888     // If the register name is one of those that appear in the condition below
3889     // and the special register builtin being used is one of the write builtins,
3890     // then we require that the argument provided for writing to the register
3891     // is an integer constant expression. This is because it will be lowered to
3892     // an MSR (immediate) instruction, so we need to know the immediate at
3893     // compile time.
3894     if (TheCall->getNumArgs() != 2)
3895       return false;
3896
3897     std::string RegLower = Reg.lower();
3898     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3899         RegLower != "pan" && RegLower != "uao")
3900       return false;
3901
3902     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3903   }
3904
3905   return false;
3906 }
3907
3908 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3909 /// This checks that the target supports __builtin_longjmp and
3910 /// that val is a constant 1.
3911 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
3912   if (!Context.getTargetInfo().hasSjLjLowering())
3913     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3914              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3915
3916   Expr *Arg = TheCall->getArg(1);
3917   llvm::APSInt Result;
3918
3919   // TODO: This is less than ideal. Overload this to take a value.
3920   if (SemaBuiltinConstantArg(TheCall, 1, Result))
3921     return true;
3922   
3923   if (Result != 1)
3924     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3925              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3926
3927   return false;
3928 }
3929
3930 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3931 /// This checks that the target supports __builtin_setjmp.
3932 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3933   if (!Context.getTargetInfo().hasSjLjLowering())
3934     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3935              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3936   return false;
3937 }
3938
3939 namespace {
3940 class UncoveredArgHandler {
3941   enum { Unknown = -1, AllCovered = -2 };
3942   signed FirstUncoveredArg;
3943   SmallVector<const Expr *, 4> DiagnosticExprs;
3944
3945 public:
3946   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3947
3948   bool hasUncoveredArg() const {
3949     return (FirstUncoveredArg >= 0);
3950   }
3951
3952   unsigned getUncoveredArg() const {
3953     assert(hasUncoveredArg() && "no uncovered argument");
3954     return FirstUncoveredArg;
3955   }
3956
3957   void setAllCovered() {
3958     // A string has been found with all arguments covered, so clear out
3959     // the diagnostics.
3960     DiagnosticExprs.clear();
3961     FirstUncoveredArg = AllCovered;
3962   }
3963
3964   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3965     assert(NewFirstUncoveredArg >= 0 && "Outside range");
3966
3967     // Don't update if a previous string covers all arguments.
3968     if (FirstUncoveredArg == AllCovered)
3969       return;
3970
3971     // UncoveredArgHandler tracks the highest uncovered argument index
3972     // and with it all the strings that match this index.
3973     if (NewFirstUncoveredArg == FirstUncoveredArg)
3974       DiagnosticExprs.push_back(StrExpr);
3975     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3976       DiagnosticExprs.clear();
3977       DiagnosticExprs.push_back(StrExpr);
3978       FirstUncoveredArg = NewFirstUncoveredArg;
3979     }
3980   }
3981
3982   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3983 };
3984
3985 enum StringLiteralCheckType {
3986   SLCT_NotALiteral,
3987   SLCT_UncheckedLiteral,
3988   SLCT_CheckedLiteral
3989 };
3990 } // end anonymous namespace
3991
3992 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3993                               const Expr *OrigFormatExpr,
3994                               ArrayRef<const Expr *> Args,
3995                               bool HasVAListArg, unsigned format_idx,
3996                               unsigned firstDataArg,
3997                               Sema::FormatStringType Type,
3998                               bool inFunctionCall,
3999                               Sema::VariadicCallType CallType,
4000                               llvm::SmallBitVector &CheckedVarArgs,
4001                               UncoveredArgHandler &UncoveredArg);
4002
4003 // Determine if an expression is a string literal or constant string.
4004 // If this function returns false on the arguments to a function expecting a
4005 // format string, we will usually need to emit a warning.
4006 // True string literals are then checked by CheckFormatString.
4007 static StringLiteralCheckType
4008 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4009                       bool HasVAListArg, unsigned format_idx,
4010                       unsigned firstDataArg, Sema::FormatStringType Type,
4011                       Sema::VariadicCallType CallType, bool InFunctionCall,
4012                       llvm::SmallBitVector &CheckedVarArgs,
4013                       UncoveredArgHandler &UncoveredArg) {
4014  tryAgain:
4015   if (E->isTypeDependent() || E->isValueDependent())
4016     return SLCT_NotALiteral;
4017
4018   E = E->IgnoreParenCasts();
4019
4020   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4021     // Technically -Wformat-nonliteral does not warn about this case.
4022     // The behavior of printf and friends in this case is implementation
4023     // dependent.  Ideally if the format string cannot be null then
4024     // it should have a 'nonnull' attribute in the function prototype.
4025     return SLCT_UncheckedLiteral;
4026
4027   switch (E->getStmtClass()) {
4028   case Stmt::BinaryConditionalOperatorClass:
4029   case Stmt::ConditionalOperatorClass: {
4030     // The expression is a literal if both sub-expressions were, and it was
4031     // completely checked only if both sub-expressions were checked.
4032     const AbstractConditionalOperator *C =
4033         cast<AbstractConditionalOperator>(E);
4034
4035     // Determine whether it is necessary to check both sub-expressions, for
4036     // example, because the condition expression is a constant that can be
4037     // evaluated at compile time.
4038     bool CheckLeft = true, CheckRight = true;
4039
4040     bool Cond;
4041     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4042       if (Cond)
4043         CheckRight = false;
4044       else
4045         CheckLeft = false;
4046     }
4047
4048     StringLiteralCheckType Left;
4049     if (!CheckLeft)
4050       Left = SLCT_UncheckedLiteral;
4051     else {
4052       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4053                                    HasVAListArg, format_idx, firstDataArg,
4054                                    Type, CallType, InFunctionCall,
4055                                    CheckedVarArgs, UncoveredArg);
4056       if (Left == SLCT_NotALiteral || !CheckRight)
4057         return Left;
4058     }
4059
4060     StringLiteralCheckType Right =
4061         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4062                               HasVAListArg, format_idx, firstDataArg,
4063                               Type, CallType, InFunctionCall, CheckedVarArgs,
4064                               UncoveredArg);
4065
4066     return (CheckLeft && Left < Right) ? Left : Right;
4067   }
4068
4069   case Stmt::ImplicitCastExprClass: {
4070     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4071     goto tryAgain;
4072   }
4073
4074   case Stmt::OpaqueValueExprClass:
4075     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4076       E = src;
4077       goto tryAgain;
4078     }
4079     return SLCT_NotALiteral;
4080
4081   case Stmt::PredefinedExprClass:
4082     // While __func__, etc., are technically not string literals, they
4083     // cannot contain format specifiers and thus are not a security
4084     // liability.
4085     return SLCT_UncheckedLiteral;
4086       
4087   case Stmt::DeclRefExprClass: {
4088     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4089
4090     // As an exception, do not flag errors for variables binding to
4091     // const string literals.
4092     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4093       bool isConstant = false;
4094       QualType T = DR->getType();
4095
4096       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4097         isConstant = AT->getElementType().isConstant(S.Context);
4098       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4099         isConstant = T.isConstant(S.Context) &&
4100                      PT->getPointeeType().isConstant(S.Context);
4101       } else if (T->isObjCObjectPointerType()) {
4102         // In ObjC, there is usually no "const ObjectPointer" type,
4103         // so don't check if the pointee type is constant.
4104         isConstant = T.isConstant(S.Context);
4105       }
4106
4107       if (isConstant) {
4108         if (const Expr *Init = VD->getAnyInitializer()) {
4109           // Look through initializers like const char c[] = { "foo" }
4110           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4111             if (InitList->isStringLiteralInit())
4112               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4113           }
4114           return checkFormatStringExpr(S, Init, Args,
4115                                        HasVAListArg, format_idx,
4116                                        firstDataArg, Type, CallType,
4117                                        /*InFunctionCall*/false, CheckedVarArgs,
4118                                        UncoveredArg);
4119         }
4120       }
4121
4122       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4123       // special check to see if the format string is a function parameter
4124       // of the function calling the printf function.  If the function
4125       // has an attribute indicating it is a printf-like function, then we
4126       // should suppress warnings concerning non-literals being used in a call
4127       // to a vprintf function.  For example:
4128       //
4129       // void
4130       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4131       //      va_list ap;
4132       //      va_start(ap, fmt);
4133       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4134       //      ...
4135       // }
4136       if (HasVAListArg) {
4137         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4138           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4139             int PVIndex = PV->getFunctionScopeIndex() + 1;
4140             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4141               // adjust for implicit parameter
4142               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4143                 if (MD->isInstance())
4144                   ++PVIndex;
4145               // We also check if the formats are compatible.
4146               // We can't pass a 'scanf' string to a 'printf' function.
4147               if (PVIndex == PVFormat->getFormatIdx() &&
4148                   Type == S.GetFormatStringType(PVFormat))
4149                 return SLCT_UncheckedLiteral;
4150             }
4151           }
4152         }
4153       }
4154     }
4155
4156     return SLCT_NotALiteral;
4157   }
4158
4159   case Stmt::CallExprClass:
4160   case Stmt::CXXMemberCallExprClass: {
4161     const CallExpr *CE = cast<CallExpr>(E);
4162     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4163       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4164         unsigned ArgIndex = FA->getFormatIdx();
4165         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4166           if (MD->isInstance())
4167             --ArgIndex;
4168         const Expr *Arg = CE->getArg(ArgIndex - 1);
4169
4170         return checkFormatStringExpr(S, Arg, Args,
4171                                      HasVAListArg, format_idx, firstDataArg,
4172                                      Type, CallType, InFunctionCall,
4173                                      CheckedVarArgs, UncoveredArg);
4174       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4175         unsigned BuiltinID = FD->getBuiltinID();
4176         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4177             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4178           const Expr *Arg = CE->getArg(0);
4179           return checkFormatStringExpr(S, Arg, Args,
4180                                        HasVAListArg, format_idx,
4181                                        firstDataArg, Type, CallType,
4182                                        InFunctionCall, CheckedVarArgs,
4183                                        UncoveredArg);
4184         }
4185       }
4186     }
4187
4188     return SLCT_NotALiteral;
4189   }
4190   case Stmt::ObjCStringLiteralClass:
4191   case Stmt::StringLiteralClass: {
4192     const StringLiteral *StrE = nullptr;
4193
4194     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4195       StrE = ObjCFExpr->getString();
4196     else
4197       StrE = cast<StringLiteral>(E);
4198
4199     if (StrE) {
4200       CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
4201                         firstDataArg, Type, InFunctionCall, CallType,
4202                         CheckedVarArgs, UncoveredArg);
4203       return SLCT_CheckedLiteral;
4204     }
4205
4206     return SLCT_NotALiteral;
4207   }
4208
4209   default:
4210     return SLCT_NotALiteral;
4211   }
4212 }
4213
4214 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4215   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4216   .Case("scanf", FST_Scanf)
4217   .Cases("printf", "printf0", FST_Printf)
4218   .Cases("NSString", "CFString", FST_NSString)
4219   .Case("strftime", FST_Strftime)
4220   .Case("strfmon", FST_Strfmon)
4221   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4222   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4223   .Case("os_trace", FST_OSTrace)
4224   .Default(FST_Unknown);
4225 }
4226
4227 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4228 /// functions) for correct use of format strings.
4229 /// Returns true if a format string has been fully checked.
4230 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4231                                 ArrayRef<const Expr *> Args,
4232                                 bool IsCXXMember,
4233                                 VariadicCallType CallType,
4234                                 SourceLocation Loc, SourceRange Range,
4235                                 llvm::SmallBitVector &CheckedVarArgs) {
4236   FormatStringInfo FSI;
4237   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4238     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4239                                 FSI.FirstDataArg, GetFormatStringType(Format),
4240                                 CallType, Loc, Range, CheckedVarArgs);
4241   return false;
4242 }
4243
4244 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4245                                 bool HasVAListArg, unsigned format_idx,
4246                                 unsigned firstDataArg, FormatStringType Type,
4247                                 VariadicCallType CallType,
4248                                 SourceLocation Loc, SourceRange Range,
4249                                 llvm::SmallBitVector &CheckedVarArgs) {
4250   // CHECK: printf/scanf-like function is called with no format string.
4251   if (format_idx >= Args.size()) {
4252     Diag(Loc, diag::warn_missing_format_string) << Range;
4253     return false;
4254   }
4255
4256   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4257
4258   // CHECK: format string is not a string literal.
4259   //
4260   // Dynamically generated format strings are difficult to
4261   // automatically vet at compile time.  Requiring that format strings
4262   // are string literals: (1) permits the checking of format strings by
4263   // the compiler and thereby (2) can practically remove the source of
4264   // many format string exploits.
4265
4266   // Format string can be either ObjC string (e.g. @"%d") or
4267   // C string (e.g. "%d")
4268   // ObjC string uses the same format specifiers as C string, so we can use
4269   // the same format string checking logic for both ObjC and C strings.
4270   UncoveredArgHandler UncoveredArg;
4271   StringLiteralCheckType CT =
4272       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4273                             format_idx, firstDataArg, Type, CallType,
4274                             /*IsFunctionCall*/true, CheckedVarArgs,
4275                             UncoveredArg);
4276
4277   // Generate a diagnostic where an uncovered argument is detected.
4278   if (UncoveredArg.hasUncoveredArg()) {
4279     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4280     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4281     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4282   }
4283
4284   if (CT != SLCT_NotALiteral)
4285     // Literal format string found, check done!
4286     return CT == SLCT_CheckedLiteral;
4287
4288   // Strftime is particular as it always uses a single 'time' argument,
4289   // so it is safe to pass a non-literal string.
4290   if (Type == FST_Strftime)
4291     return false;
4292
4293   // Do not emit diag when the string param is a macro expansion and the
4294   // format is either NSString or CFString. This is a hack to prevent
4295   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4296   // which are usually used in place of NS and CF string literals.
4297   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4298   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4299     return false;
4300
4301   // If there are no arguments specified, warn with -Wformat-security, otherwise
4302   // warn only with -Wformat-nonliteral.
4303   if (Args.size() == firstDataArg) {
4304     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4305       << OrigFormatExpr->getSourceRange();
4306     switch (Type) {
4307     default:
4308       break;
4309     case FST_Kprintf:
4310     case FST_FreeBSDKPrintf:
4311     case FST_Printf:
4312       Diag(FormatLoc, diag::note_format_security_fixit)
4313         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4314       break;
4315     case FST_NSString:
4316       Diag(FormatLoc, diag::note_format_security_fixit)
4317         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4318       break;
4319     }
4320   } else {
4321     Diag(FormatLoc, diag::warn_format_nonliteral)
4322       << OrigFormatExpr->getSourceRange();
4323   }
4324   return false;
4325 }
4326
4327 namespace {
4328 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4329 protected:
4330   Sema &S;
4331   const StringLiteral *FExpr;
4332   const Expr *OrigFormatExpr;
4333   const unsigned FirstDataArg;
4334   const unsigned NumDataArgs;
4335   const char *Beg; // Start of format string.
4336   const bool HasVAListArg;
4337   ArrayRef<const Expr *> Args;
4338   unsigned FormatIdx;
4339   llvm::SmallBitVector CoveredArgs;
4340   bool usesPositionalArgs;
4341   bool atFirstArg;
4342   bool inFunctionCall;
4343   Sema::VariadicCallType CallType;
4344   llvm::SmallBitVector &CheckedVarArgs;
4345   UncoveredArgHandler &UncoveredArg;
4346
4347 public:
4348   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
4349                      const Expr *origFormatExpr, unsigned firstDataArg,
4350                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4351                      ArrayRef<const Expr *> Args,
4352                      unsigned formatIdx, bool inFunctionCall,
4353                      Sema::VariadicCallType callType,
4354                      llvm::SmallBitVector &CheckedVarArgs,
4355                      UncoveredArgHandler &UncoveredArg)
4356     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
4357       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4358       Beg(beg), HasVAListArg(hasVAListArg),
4359       Args(Args), FormatIdx(formatIdx),
4360       usesPositionalArgs(false), atFirstArg(true),
4361       inFunctionCall(inFunctionCall), CallType(callType),
4362       CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4363     CoveredArgs.resize(numDataArgs);
4364     CoveredArgs.reset();
4365   }
4366
4367   void DoneProcessing();
4368
4369   void HandleIncompleteSpecifier(const char *startSpecifier,
4370                                  unsigned specifierLen) override;
4371
4372   void HandleInvalidLengthModifier(
4373                            const analyze_format_string::FormatSpecifier &FS,
4374                            const analyze_format_string::ConversionSpecifier &CS,
4375                            const char *startSpecifier, unsigned specifierLen,
4376                            unsigned DiagID);
4377
4378   void HandleNonStandardLengthModifier(
4379                     const analyze_format_string::FormatSpecifier &FS,
4380                     const char *startSpecifier, unsigned specifierLen);
4381
4382   void HandleNonStandardConversionSpecifier(
4383                     const analyze_format_string::ConversionSpecifier &CS,
4384                     const char *startSpecifier, unsigned specifierLen);
4385
4386   void HandlePosition(const char *startPos, unsigned posLen) override;
4387
4388   void HandleInvalidPosition(const char *startSpecifier,
4389                              unsigned specifierLen,
4390                              analyze_format_string::PositionContext p) override;
4391
4392   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4393
4394   void HandleNullChar(const char *nullCharacter) override;
4395
4396   template <typename Range>
4397   static void
4398   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4399                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4400                        bool IsStringLocation, Range StringRange,
4401                        ArrayRef<FixItHint> Fixit = None);
4402
4403 protected:
4404   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4405                                         const char *startSpec,
4406                                         unsigned specifierLen,
4407                                         const char *csStart, unsigned csLen);
4408
4409   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4410                                          const char *startSpec,
4411                                          unsigned specifierLen);
4412   
4413   SourceRange getFormatStringRange();
4414   CharSourceRange getSpecifierRange(const char *startSpecifier,
4415                                     unsigned specifierLen);
4416   SourceLocation getLocationOfByte(const char *x);
4417
4418   const Expr *getDataArg(unsigned i) const;
4419   
4420   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4421                     const analyze_format_string::ConversionSpecifier &CS,
4422                     const char *startSpecifier, unsigned specifierLen,
4423                     unsigned argIndex);
4424
4425   template <typename Range>
4426   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4427                             bool IsStringLocation, Range StringRange,
4428                             ArrayRef<FixItHint> Fixit = None);
4429 };
4430 } // end anonymous namespace
4431
4432 SourceRange CheckFormatHandler::getFormatStringRange() {
4433   return OrigFormatExpr->getSourceRange();
4434 }
4435
4436 CharSourceRange CheckFormatHandler::
4437 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4438   SourceLocation Start = getLocationOfByte(startSpecifier);
4439   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4440
4441   // Advance the end SourceLocation by one due to half-open ranges.
4442   End = End.getLocWithOffset(1);
4443
4444   return CharSourceRange::getCharRange(Start, End);
4445 }
4446
4447 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4448   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
4449 }
4450
4451 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4452                                                    unsigned specifierLen){
4453   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4454                        getLocationOfByte(startSpecifier),
4455                        /*IsStringLocation*/true,
4456                        getSpecifierRange(startSpecifier, specifierLen));
4457 }
4458
4459 void CheckFormatHandler::HandleInvalidLengthModifier(
4460     const analyze_format_string::FormatSpecifier &FS,
4461     const analyze_format_string::ConversionSpecifier &CS,
4462     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4463   using namespace analyze_format_string;
4464
4465   const LengthModifier &LM = FS.getLengthModifier();
4466   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4467
4468   // See if we know how to fix this length modifier.
4469   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4470   if (FixedLM) {
4471     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4472                          getLocationOfByte(LM.getStart()),
4473                          /*IsStringLocation*/true,
4474                          getSpecifierRange(startSpecifier, specifierLen));
4475
4476     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4477       << FixedLM->toString()
4478       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4479
4480   } else {
4481     FixItHint Hint;
4482     if (DiagID == diag::warn_format_nonsensical_length)
4483       Hint = FixItHint::CreateRemoval(LMRange);
4484
4485     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4486                          getLocationOfByte(LM.getStart()),
4487                          /*IsStringLocation*/true,
4488                          getSpecifierRange(startSpecifier, specifierLen),
4489                          Hint);
4490   }
4491 }
4492
4493 void CheckFormatHandler::HandleNonStandardLengthModifier(
4494     const analyze_format_string::FormatSpecifier &FS,
4495     const char *startSpecifier, unsigned specifierLen) {
4496   using namespace analyze_format_string;
4497
4498   const LengthModifier &LM = FS.getLengthModifier();
4499   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4500
4501   // See if we know how to fix this length modifier.
4502   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4503   if (FixedLM) {
4504     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4505                            << LM.toString() << 0,
4506                          getLocationOfByte(LM.getStart()),
4507                          /*IsStringLocation*/true,
4508                          getSpecifierRange(startSpecifier, specifierLen));
4509
4510     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4511       << FixedLM->toString()
4512       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4513
4514   } else {
4515     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4516                            << LM.toString() << 0,
4517                          getLocationOfByte(LM.getStart()),
4518                          /*IsStringLocation*/true,
4519                          getSpecifierRange(startSpecifier, specifierLen));
4520   }
4521 }
4522
4523 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4524     const analyze_format_string::ConversionSpecifier &CS,
4525     const char *startSpecifier, unsigned specifierLen) {
4526   using namespace analyze_format_string;
4527
4528   // See if we know how to fix this conversion specifier.
4529   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
4530   if (FixedCS) {
4531     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4532                           << CS.toString() << /*conversion specifier*/1,
4533                          getLocationOfByte(CS.getStart()),
4534                          /*IsStringLocation*/true,
4535                          getSpecifierRange(startSpecifier, specifierLen));
4536
4537     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4538     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4539       << FixedCS->toString()
4540       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4541   } else {
4542     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4543                           << CS.toString() << /*conversion specifier*/1,
4544                          getLocationOfByte(CS.getStart()),
4545                          /*IsStringLocation*/true,
4546                          getSpecifierRange(startSpecifier, specifierLen));
4547   }
4548 }
4549
4550 void CheckFormatHandler::HandlePosition(const char *startPos,
4551                                         unsigned posLen) {
4552   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4553                                getLocationOfByte(startPos),
4554                                /*IsStringLocation*/true,
4555                                getSpecifierRange(startPos, posLen));
4556 }
4557
4558 void
4559 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4560                                      analyze_format_string::PositionContext p) {
4561   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4562                          << (unsigned) p,
4563                        getLocationOfByte(startPos), /*IsStringLocation*/true,
4564                        getSpecifierRange(startPos, posLen));
4565 }
4566
4567 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
4568                                             unsigned posLen) {
4569   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4570                                getLocationOfByte(startPos),
4571                                /*IsStringLocation*/true,
4572                                getSpecifierRange(startPos, posLen));
4573 }
4574
4575 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
4576   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4577     // The presence of a null character is likely an error.
4578     EmitFormatDiagnostic(
4579       S.PDiag(diag::warn_printf_format_string_contains_null_char),
4580       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4581       getFormatStringRange());
4582   }
4583 }
4584
4585 // Note that this may return NULL if there was an error parsing or building
4586 // one of the argument expressions.
4587 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
4588   return Args[FirstDataArg + i];
4589 }
4590
4591 void CheckFormatHandler::DoneProcessing() {
4592   // Does the number of data arguments exceed the number of
4593   // format conversions in the format string?
4594   if (!HasVAListArg) {
4595       // Find any arguments that weren't covered.
4596     CoveredArgs.flip();
4597     signed notCoveredArg = CoveredArgs.find_first();
4598     if (notCoveredArg >= 0) {
4599       assert((unsigned)notCoveredArg < NumDataArgs);
4600       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4601     } else {
4602       UncoveredArg.setAllCovered();
4603     }
4604   }
4605 }
4606
4607 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4608                                    const Expr *ArgExpr) {
4609   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4610          "Invalid state");
4611
4612   if (!ArgExpr)
4613     return;
4614
4615   SourceLocation Loc = ArgExpr->getLocStart();
4616
4617   if (S.getSourceManager().isInSystemMacro(Loc))
4618     return;
4619
4620   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4621   for (auto E : DiagnosticExprs)
4622     PDiag << E->getSourceRange();
4623
4624   CheckFormatHandler::EmitFormatDiagnostic(
4625                                   S, IsFunctionCall, DiagnosticExprs[0],
4626                                   PDiag, Loc, /*IsStringLocation*/false,
4627                                   DiagnosticExprs[0]->getSourceRange());
4628 }
4629
4630 bool
4631 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4632                                                      SourceLocation Loc,
4633                                                      const char *startSpec,
4634                                                      unsigned specifierLen,
4635                                                      const char *csStart,
4636                                                      unsigned csLen) {
4637   bool keepGoing = true;
4638   if (argIndex < NumDataArgs) {
4639     // Consider the argument coverered, even though the specifier doesn't
4640     // make sense.
4641     CoveredArgs.set(argIndex);
4642   }
4643   else {
4644     // If argIndex exceeds the number of data arguments we
4645     // don't issue a warning because that is just a cascade of warnings (and
4646     // they may have intended '%%' anyway). We don't want to continue processing
4647     // the format string after this point, however, as we will like just get
4648     // gibberish when trying to match arguments.
4649     keepGoing = false;
4650   }
4651
4652   StringRef Specifier(csStart, csLen);
4653
4654   // If the specifier in non-printable, it could be the first byte of a UTF-8
4655   // sequence. In that case, print the UTF-8 code point. If not, print the byte
4656   // hex value.
4657   std::string CodePointStr;
4658   if (!llvm::sys::locale::isPrint(*csStart)) {
4659     UTF32 CodePoint;
4660     const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4661     const UTF8 *E =
4662         reinterpret_cast<const UTF8 *>(csStart + csLen);
4663     ConversionResult Result =
4664         llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4665
4666     if (Result != conversionOK) {
4667       unsigned char FirstChar = *csStart;
4668       CodePoint = (UTF32)FirstChar;
4669     }
4670
4671     llvm::raw_string_ostream OS(CodePointStr);
4672     if (CodePoint < 256)
4673       OS << "\\x" << llvm::format("%02x", CodePoint);
4674     else if (CodePoint <= 0xFFFF)
4675       OS << "\\u" << llvm::format("%04x", CodePoint);
4676     else
4677       OS << "\\U" << llvm::format("%08x", CodePoint);
4678     OS.flush();
4679     Specifier = CodePointStr;
4680   }
4681
4682   EmitFormatDiagnostic(
4683       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4684       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4685
4686   return keepGoing;
4687 }
4688
4689 void
4690 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4691                                                       const char *startSpec,
4692                                                       unsigned specifierLen) {
4693   EmitFormatDiagnostic(
4694     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4695     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4696 }
4697
4698 bool
4699 CheckFormatHandler::CheckNumArgs(
4700   const analyze_format_string::FormatSpecifier &FS,
4701   const analyze_format_string::ConversionSpecifier &CS,
4702   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4703
4704   if (argIndex >= NumDataArgs) {
4705     PartialDiagnostic PDiag = FS.usesPositionalArg()
4706       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4707            << (argIndex+1) << NumDataArgs)
4708       : S.PDiag(diag::warn_printf_insufficient_data_args);
4709     EmitFormatDiagnostic(
4710       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4711       getSpecifierRange(startSpecifier, specifierLen));
4712
4713     // Since more arguments than conversion tokens are given, by extension
4714     // all arguments are covered, so mark this as so.
4715     UncoveredArg.setAllCovered();
4716     return false;
4717   }
4718   return true;
4719 }
4720
4721 template<typename Range>
4722 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4723                                               SourceLocation Loc,
4724                                               bool IsStringLocation,
4725                                               Range StringRange,
4726                                               ArrayRef<FixItHint> FixIt) {
4727   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4728                        Loc, IsStringLocation, StringRange, FixIt);
4729 }
4730
4731 /// \brief If the format string is not within the funcion call, emit a note
4732 /// so that the function call and string are in diagnostic messages.
4733 ///
4734 /// \param InFunctionCall if true, the format string is within the function
4735 /// call and only one diagnostic message will be produced.  Otherwise, an
4736 /// extra note will be emitted pointing to location of the format string.
4737 ///
4738 /// \param ArgumentExpr the expression that is passed as the format string
4739 /// argument in the function call.  Used for getting locations when two
4740 /// diagnostics are emitted.
4741 ///
4742 /// \param PDiag the callee should already have provided any strings for the
4743 /// diagnostic message.  This function only adds locations and fixits
4744 /// to diagnostics.
4745 ///
4746 /// \param Loc primary location for diagnostic.  If two diagnostics are
4747 /// required, one will be at Loc and a new SourceLocation will be created for
4748 /// the other one.
4749 ///
4750 /// \param IsStringLocation if true, Loc points to the format string should be
4751 /// used for the note.  Otherwise, Loc points to the argument list and will
4752 /// be used with PDiag.
4753 ///
4754 /// \param StringRange some or all of the string to highlight.  This is
4755 /// templated so it can accept either a CharSourceRange or a SourceRange.
4756 ///
4757 /// \param FixIt optional fix it hint for the format string.
4758 template <typename Range>
4759 void CheckFormatHandler::EmitFormatDiagnostic(
4760     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4761     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4762     Range StringRange, ArrayRef<FixItHint> FixIt) {
4763   if (InFunctionCall) {
4764     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4765     D << StringRange;
4766     D << FixIt;
4767   } else {
4768     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4769       << ArgumentExpr->getSourceRange();
4770
4771     const Sema::SemaDiagnosticBuilder &Note =
4772       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4773              diag::note_format_string_defined);
4774
4775     Note << StringRange;
4776     Note << FixIt;
4777   }
4778 }
4779
4780 //===--- CHECK: Printf format string checking ------------------------------===//
4781
4782 namespace {
4783 class CheckPrintfHandler : public CheckFormatHandler {
4784   bool ObjCContext;
4785
4786 public:
4787   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4788                      const Expr *origFormatExpr, unsigned firstDataArg,
4789                      unsigned numDataArgs, bool isObjC,
4790                      const char *beg, bool hasVAListArg,
4791                      ArrayRef<const Expr *> Args,
4792                      unsigned formatIdx, bool inFunctionCall,
4793                      Sema::VariadicCallType CallType,
4794                      llvm::SmallBitVector &CheckedVarArgs,
4795                      UncoveredArgHandler &UncoveredArg)
4796     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4797                          numDataArgs, beg, hasVAListArg, Args,
4798                          formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4799                          UncoveredArg),
4800       ObjCContext(isObjC)
4801   {}
4802
4803   bool HandleInvalidPrintfConversionSpecifier(
4804                                       const analyze_printf::PrintfSpecifier &FS,
4805                                       const char *startSpecifier,
4806                                       unsigned specifierLen) override;
4807
4808   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4809                              const char *startSpecifier,
4810                              unsigned specifierLen) override;
4811   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4812                        const char *StartSpecifier,
4813                        unsigned SpecifierLen,
4814                        const Expr *E);
4815
4816   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4817                     const char *startSpecifier, unsigned specifierLen);
4818   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4819                            const analyze_printf::OptionalAmount &Amt,
4820                            unsigned type,
4821                            const char *startSpecifier, unsigned specifierLen);
4822   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4823                   const analyze_printf::OptionalFlag &flag,
4824                   const char *startSpecifier, unsigned specifierLen);
4825   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4826                          const analyze_printf::OptionalFlag &ignoredFlag,
4827                          const analyze_printf::OptionalFlag &flag,
4828                          const char *startSpecifier, unsigned specifierLen);
4829   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
4830                            const Expr *E);
4831                            
4832   void HandleEmptyObjCModifierFlag(const char *startFlag,
4833                                    unsigned flagLen) override;
4834
4835   void HandleInvalidObjCModifierFlag(const char *startFlag,
4836                                             unsigned flagLen) override;
4837
4838   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4839                                            const char *flagsEnd,
4840                                            const char *conversionPosition) 
4841                                              override;
4842 };
4843 } // end anonymous namespace
4844
4845 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4846                                       const analyze_printf::PrintfSpecifier &FS,
4847                                       const char *startSpecifier,
4848                                       unsigned specifierLen) {
4849   const analyze_printf::PrintfConversionSpecifier &CS =
4850     FS.getConversionSpecifier();
4851   
4852   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4853                                           getLocationOfByte(CS.getStart()),
4854                                           startSpecifier, specifierLen,
4855                                           CS.getStart(), CS.getLength());
4856 }
4857
4858 bool CheckPrintfHandler::HandleAmount(
4859                                const analyze_format_string::OptionalAmount &Amt,
4860                                unsigned k, const char *startSpecifier,
4861                                unsigned specifierLen) {
4862   if (Amt.hasDataArgument()) {
4863     if (!HasVAListArg) {
4864       unsigned argIndex = Amt.getArgIndex();
4865       if (argIndex >= NumDataArgs) {
4866         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4867                                << k,
4868                              getLocationOfByte(Amt.getStart()),
4869                              /*IsStringLocation*/true,
4870                              getSpecifierRange(startSpecifier, specifierLen));
4871         // Don't do any more checking.  We will just emit
4872         // spurious errors.
4873         return false;
4874       }
4875
4876       // Type check the data argument.  It should be an 'int'.
4877       // Although not in conformance with C99, we also allow the argument to be
4878       // an 'unsigned int' as that is a reasonably safe case.  GCC also
4879       // doesn't emit a warning for that case.
4880       CoveredArgs.set(argIndex);
4881       const Expr *Arg = getDataArg(argIndex);
4882       if (!Arg)
4883         return false;
4884
4885       QualType T = Arg->getType();
4886
4887       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4888       assert(AT.isValid());
4889
4890       if (!AT.matchesType(S.Context, T)) {
4891         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
4892                                << k << AT.getRepresentativeTypeName(S.Context)
4893                                << T << Arg->getSourceRange(),
4894                              getLocationOfByte(Amt.getStart()),
4895                              /*IsStringLocation*/true,
4896                              getSpecifierRange(startSpecifier, specifierLen));
4897         // Don't do any more checking.  We will just emit
4898         // spurious errors.
4899         return false;
4900       }
4901     }
4902   }
4903   return true;
4904 }
4905
4906 void CheckPrintfHandler::HandleInvalidAmount(
4907                                       const analyze_printf::PrintfSpecifier &FS,
4908                                       const analyze_printf::OptionalAmount &Amt,
4909                                       unsigned type,
4910                                       const char *startSpecifier,
4911                                       unsigned specifierLen) {
4912   const analyze_printf::PrintfConversionSpecifier &CS =
4913     FS.getConversionSpecifier();
4914
4915   FixItHint fixit =
4916     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4917       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4918                                  Amt.getConstantLength()))
4919       : FixItHint();
4920
4921   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4922                          << type << CS.toString(),
4923                        getLocationOfByte(Amt.getStart()),
4924                        /*IsStringLocation*/true,
4925                        getSpecifierRange(startSpecifier, specifierLen),
4926                        fixit);
4927 }
4928
4929 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4930                                     const analyze_printf::OptionalFlag &flag,
4931                                     const char *startSpecifier,
4932                                     unsigned specifierLen) {
4933   // Warn about pointless flag with a fixit removal.
4934   const analyze_printf::PrintfConversionSpecifier &CS =
4935     FS.getConversionSpecifier();
4936   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4937                          << flag.toString() << CS.toString(),
4938                        getLocationOfByte(flag.getPosition()),
4939                        /*IsStringLocation*/true,
4940                        getSpecifierRange(startSpecifier, specifierLen),
4941                        FixItHint::CreateRemoval(
4942                          getSpecifierRange(flag.getPosition(), 1)));
4943 }
4944
4945 void CheckPrintfHandler::HandleIgnoredFlag(
4946                                 const analyze_printf::PrintfSpecifier &FS,
4947                                 const analyze_printf::OptionalFlag &ignoredFlag,
4948                                 const analyze_printf::OptionalFlag &flag,
4949                                 const char *startSpecifier,
4950                                 unsigned specifierLen) {
4951   // Warn about ignored flag with a fixit removal.
4952   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4953                          << ignoredFlag.toString() << flag.toString(),
4954                        getLocationOfByte(ignoredFlag.getPosition()),
4955                        /*IsStringLocation*/true,
4956                        getSpecifierRange(startSpecifier, specifierLen),
4957                        FixItHint::CreateRemoval(
4958                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
4959 }
4960
4961 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4962 //                            bool IsStringLocation, Range StringRange,
4963 //                            ArrayRef<FixItHint> Fixit = None);
4964                             
4965 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4966                                                      unsigned flagLen) {
4967   // Warn about an empty flag.
4968   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4969                        getLocationOfByte(startFlag),
4970                        /*IsStringLocation*/true,
4971                        getSpecifierRange(startFlag, flagLen));
4972 }
4973
4974 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4975                                                        unsigned flagLen) {
4976   // Warn about an invalid flag.
4977   auto Range = getSpecifierRange(startFlag, flagLen);
4978   StringRef flag(startFlag, flagLen);
4979   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4980                       getLocationOfByte(startFlag),
4981                       /*IsStringLocation*/true,
4982                       Range, FixItHint::CreateRemoval(Range));
4983 }
4984
4985 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4986     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4987     // Warn about using '[...]' without a '@' conversion.
4988     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4989     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4990     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4991                          getLocationOfByte(conversionPosition),
4992                          /*IsStringLocation*/true,
4993                          Range, FixItHint::CreateRemoval(Range));
4994 }
4995
4996 // Determines if the specified is a C++ class or struct containing
4997 // a member with the specified name and kind (e.g. a CXXMethodDecl named
4998 // "c_str()").
4999 template<typename MemberKind>
5000 static llvm::SmallPtrSet<MemberKind*, 1>
5001 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5002   const RecordType *RT = Ty->getAs<RecordType>();
5003   llvm::SmallPtrSet<MemberKind*, 1> Results;
5004
5005   if (!RT)
5006     return Results;
5007   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5008   if (!RD || !RD->getDefinition())
5009     return Results;
5010
5011   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5012                  Sema::LookupMemberName);
5013   R.suppressDiagnostics();
5014
5015   // We just need to include all members of the right kind turned up by the
5016   // filter, at this point.
5017   if (S.LookupQualifiedName(R, RT->getDecl()))
5018     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5019       NamedDecl *decl = (*I)->getUnderlyingDecl();
5020       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5021         Results.insert(FK);
5022     }
5023   return Results;
5024 }
5025
5026 /// Check if we could call '.c_str()' on an object.
5027 ///
5028 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5029 /// allow the call, or if it would be ambiguous).
5030 bool Sema::hasCStrMethod(const Expr *E) {
5031   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5032   MethodSet Results =
5033       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5034   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5035        MI != ME; ++MI)
5036     if ((*MI)->getMinRequiredArguments() == 0)
5037       return true;
5038   return false;
5039 }
5040
5041 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5042 // better diagnostic if so. AT is assumed to be valid.
5043 // Returns true when a c_str() conversion method is found.
5044 bool CheckPrintfHandler::checkForCStrMembers(
5045     const analyze_printf::ArgType &AT, const Expr *E) {
5046   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5047
5048   MethodSet Results =
5049       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5050
5051   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5052        MI != ME; ++MI) {
5053     const CXXMethodDecl *Method = *MI;
5054     if (Method->getMinRequiredArguments() == 0 &&
5055         AT.matchesType(S.Context, Method->getReturnType())) {
5056       // FIXME: Suggest parens if the expression needs them.
5057       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5058       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5059           << "c_str()"
5060           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5061       return true;
5062     }
5063   }
5064
5065   return false;
5066 }
5067
5068 bool
5069 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5070                                             &FS,
5071                                           const char *startSpecifier,
5072                                           unsigned specifierLen) {
5073   using namespace analyze_format_string;
5074   using namespace analyze_printf;  
5075   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5076
5077   if (FS.consumesDataArgument()) {
5078     if (atFirstArg) {
5079         atFirstArg = false;
5080         usesPositionalArgs = FS.usesPositionalArg();
5081     }
5082     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5083       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5084                                         startSpecifier, specifierLen);
5085       return false;
5086     }
5087   }
5088
5089   // First check if the field width, precision, and conversion specifier
5090   // have matching data arguments.
5091   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5092                     startSpecifier, specifierLen)) {
5093     return false;
5094   }
5095
5096   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5097                     startSpecifier, specifierLen)) {
5098     return false;
5099   }
5100
5101   if (!CS.consumesDataArgument()) {
5102     // FIXME: Technically specifying a precision or field width here
5103     // makes no sense.  Worth issuing a warning at some point.
5104     return true;
5105   }
5106
5107   // Consume the argument.
5108   unsigned argIndex = FS.getArgIndex();
5109   if (argIndex < NumDataArgs) {
5110     // The check to see if the argIndex is valid will come later.
5111     // We set the bit here because we may exit early from this
5112     // function if we encounter some other error.
5113     CoveredArgs.set(argIndex);
5114   }
5115
5116   // FreeBSD kernel extensions.
5117   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5118       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5119     // We need at least two arguments.
5120     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5121       return false;
5122
5123     // Claim the second argument.
5124     CoveredArgs.set(argIndex + 1);
5125
5126     // Type check the first argument (int for %b, pointer for %D)
5127     const Expr *Ex = getDataArg(argIndex);
5128     const analyze_printf::ArgType &AT =
5129       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5130         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5131     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5132       EmitFormatDiagnostic(
5133         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5134         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5135         << false << Ex->getSourceRange(),
5136         Ex->getLocStart(), /*IsStringLocation*/false,
5137         getSpecifierRange(startSpecifier, specifierLen));
5138
5139     // Type check the second argument (char * for both %b and %D)
5140     Ex = getDataArg(argIndex + 1);
5141     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5142     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5143       EmitFormatDiagnostic(
5144         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5145         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5146         << false << Ex->getSourceRange(),
5147         Ex->getLocStart(), /*IsStringLocation*/false,
5148         getSpecifierRange(startSpecifier, specifierLen));
5149
5150      return true;
5151   }
5152
5153   // Check for using an Objective-C specific conversion specifier
5154   // in a non-ObjC literal.
5155   if (!ObjCContext && CS.isObjCArg()) {
5156     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5157                                                   specifierLen);
5158   }
5159
5160   // Check for invalid use of field width
5161   if (!FS.hasValidFieldWidth()) {
5162     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5163         startSpecifier, specifierLen);
5164   }
5165
5166   // Check for invalid use of precision
5167   if (!FS.hasValidPrecision()) {
5168     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5169         startSpecifier, specifierLen);
5170   }
5171
5172   // Check each flag does not conflict with any other component.
5173   if (!FS.hasValidThousandsGroupingPrefix())
5174     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5175   if (!FS.hasValidLeadingZeros())
5176     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5177   if (!FS.hasValidPlusPrefix())
5178     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5179   if (!FS.hasValidSpacePrefix())
5180     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5181   if (!FS.hasValidAlternativeForm())
5182     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5183   if (!FS.hasValidLeftJustified())
5184     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5185
5186   // Check that flags are not ignored by another flag
5187   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5188     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5189         startSpecifier, specifierLen);
5190   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5191     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5192             startSpecifier, specifierLen);
5193
5194   // Check the length modifier is valid with the given conversion specifier.
5195   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5196     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5197                                 diag::warn_format_nonsensical_length);
5198   else if (!FS.hasStandardLengthModifier())
5199     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5200   else if (!FS.hasStandardLengthConversionCombination())
5201     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5202                                 diag::warn_format_non_standard_conversion_spec);
5203
5204   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5205     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5206
5207   // The remaining checks depend on the data arguments.
5208   if (HasVAListArg)
5209     return true;
5210
5211   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5212     return false;
5213
5214   const Expr *Arg = getDataArg(argIndex);
5215   if (!Arg)
5216     return true;
5217
5218   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5219 }
5220
5221 static bool requiresParensToAddCast(const Expr *E) {
5222   // FIXME: We should have a general way to reason about operator
5223   // precedence and whether parens are actually needed here.
5224   // Take care of a few common cases where they aren't.
5225   const Expr *Inside = E->IgnoreImpCasts();
5226   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5227     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5228
5229   switch (Inside->getStmtClass()) {
5230   case Stmt::ArraySubscriptExprClass:
5231   case Stmt::CallExprClass:
5232   case Stmt::CharacterLiteralClass:
5233   case Stmt::CXXBoolLiteralExprClass:
5234   case Stmt::DeclRefExprClass:
5235   case Stmt::FloatingLiteralClass:
5236   case Stmt::IntegerLiteralClass:
5237   case Stmt::MemberExprClass:
5238   case Stmt::ObjCArrayLiteralClass:
5239   case Stmt::ObjCBoolLiteralExprClass:
5240   case Stmt::ObjCBoxedExprClass:
5241   case Stmt::ObjCDictionaryLiteralClass:
5242   case Stmt::ObjCEncodeExprClass:
5243   case Stmt::ObjCIvarRefExprClass:
5244   case Stmt::ObjCMessageExprClass:
5245   case Stmt::ObjCPropertyRefExprClass:
5246   case Stmt::ObjCStringLiteralClass:
5247   case Stmt::ObjCSubscriptRefExprClass:
5248   case Stmt::ParenExprClass:
5249   case Stmt::StringLiteralClass:
5250   case Stmt::UnaryOperatorClass:
5251     return false;
5252   default:
5253     return true;
5254   }
5255 }
5256
5257 static std::pair<QualType, StringRef>
5258 shouldNotPrintDirectly(const ASTContext &Context,
5259                        QualType IntendedTy,
5260                        const Expr *E) {
5261   // Use a 'while' to peel off layers of typedefs.
5262   QualType TyTy = IntendedTy;
5263   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5264     StringRef Name = UserTy->getDecl()->getName();
5265     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5266       .Case("NSInteger", Context.LongTy)
5267       .Case("NSUInteger", Context.UnsignedLongTy)
5268       .Case("SInt32", Context.IntTy)
5269       .Case("UInt32", Context.UnsignedIntTy)
5270       .Default(QualType());
5271
5272     if (!CastTy.isNull())
5273       return std::make_pair(CastTy, Name);
5274
5275     TyTy = UserTy->desugar();
5276   }
5277
5278   // Strip parens if necessary.
5279   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5280     return shouldNotPrintDirectly(Context,
5281                                   PE->getSubExpr()->getType(),
5282                                   PE->getSubExpr());
5283
5284   // If this is a conditional expression, then its result type is constructed
5285   // via usual arithmetic conversions and thus there might be no necessary
5286   // typedef sugar there.  Recurse to operands to check for NSInteger &
5287   // Co. usage condition.
5288   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5289     QualType TrueTy, FalseTy;
5290     StringRef TrueName, FalseName;
5291
5292     std::tie(TrueTy, TrueName) =
5293       shouldNotPrintDirectly(Context,
5294                              CO->getTrueExpr()->getType(),
5295                              CO->getTrueExpr());
5296     std::tie(FalseTy, FalseName) =
5297       shouldNotPrintDirectly(Context,
5298                              CO->getFalseExpr()->getType(),
5299                              CO->getFalseExpr());
5300
5301     if (TrueTy == FalseTy)
5302       return std::make_pair(TrueTy, TrueName);
5303     else if (TrueTy.isNull())
5304       return std::make_pair(FalseTy, FalseName);
5305     else if (FalseTy.isNull())
5306       return std::make_pair(TrueTy, TrueName);
5307   }
5308
5309   return std::make_pair(QualType(), StringRef());
5310 }
5311
5312 bool
5313 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5314                                     const char *StartSpecifier,
5315                                     unsigned SpecifierLen,
5316                                     const Expr *E) {
5317   using namespace analyze_format_string;
5318   using namespace analyze_printf;
5319   // Now type check the data expression that matches the
5320   // format specifier.
5321   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5322                                                     ObjCContext);
5323   if (!AT.isValid())
5324     return true;
5325
5326   QualType ExprTy = E->getType();
5327   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5328     ExprTy = TET->getUnderlyingExpr()->getType();
5329   }
5330
5331   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5332
5333   if (match == analyze_printf::ArgType::Match) {
5334     return true;
5335   }
5336
5337   // Look through argument promotions for our error message's reported type.
5338   // This includes the integral and floating promotions, but excludes array
5339   // and function pointer decay; seeing that an argument intended to be a
5340   // string has type 'char [6]' is probably more confusing than 'char *'.
5341   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5342     if (ICE->getCastKind() == CK_IntegralCast ||
5343         ICE->getCastKind() == CK_FloatingCast) {
5344       E = ICE->getSubExpr();
5345       ExprTy = E->getType();
5346
5347       // Check if we didn't match because of an implicit cast from a 'char'
5348       // or 'short' to an 'int'.  This is done because printf is a varargs
5349       // function.
5350       if (ICE->getType() == S.Context.IntTy ||
5351           ICE->getType() == S.Context.UnsignedIntTy) {
5352         // All further checking is done on the subexpression.
5353         if (AT.matchesType(S.Context, ExprTy))
5354           return true;
5355       }
5356     }
5357   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5358     // Special case for 'a', which has type 'int' in C.
5359     // Note, however, that we do /not/ want to treat multibyte constants like
5360     // 'MooV' as characters! This form is deprecated but still exists.
5361     if (ExprTy == S.Context.IntTy)
5362       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5363         ExprTy = S.Context.CharTy;
5364   }
5365
5366   // Look through enums to their underlying type.
5367   bool IsEnum = false;
5368   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5369     ExprTy = EnumTy->getDecl()->getIntegerType();
5370     IsEnum = true;
5371   }
5372
5373   // %C in an Objective-C context prints a unichar, not a wchar_t.
5374   // If the argument is an integer of some kind, believe the %C and suggest
5375   // a cast instead of changing the conversion specifier.
5376   QualType IntendedTy = ExprTy;
5377   if (ObjCContext &&
5378       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5379     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5380         !ExprTy->isCharType()) {
5381       // 'unichar' is defined as a typedef of unsigned short, but we should
5382       // prefer using the typedef if it is visible.
5383       IntendedTy = S.Context.UnsignedShortTy;
5384
5385       // While we are here, check if the value is an IntegerLiteral that happens
5386       // to be within the valid range.
5387       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5388         const llvm::APInt &V = IL->getValue();
5389         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5390           return true;
5391       }
5392
5393       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5394                           Sema::LookupOrdinaryName);
5395       if (S.LookupName(Result, S.getCurScope())) {
5396         NamedDecl *ND = Result.getFoundDecl();
5397         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5398           if (TD->getUnderlyingType() == IntendedTy)
5399             IntendedTy = S.Context.getTypedefType(TD);
5400       }
5401     }
5402   }
5403
5404   // Special-case some of Darwin's platform-independence types by suggesting
5405   // casts to primitive types that are known to be large enough.
5406   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5407   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5408     QualType CastTy;
5409     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5410     if (!CastTy.isNull()) {
5411       IntendedTy = CastTy;
5412       ShouldNotPrintDirectly = true;
5413     }
5414   }
5415
5416   // We may be able to offer a FixItHint if it is a supported type.
5417   PrintfSpecifier fixedFS = FS;
5418   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
5419                                  S.Context, ObjCContext);
5420
5421   if (success) {
5422     // Get the fix string from the fixed format specifier
5423     SmallString<16> buf;
5424     llvm::raw_svector_ostream os(buf);
5425     fixedFS.toString(os);
5426
5427     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5428
5429     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5430       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5431       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5432         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5433       }
5434       // In this case, the specifier is wrong and should be changed to match
5435       // the argument.
5436       EmitFormatDiagnostic(S.PDiag(diag)
5437                                << AT.getRepresentativeTypeName(S.Context)
5438                                << IntendedTy << IsEnum << E->getSourceRange(),
5439                            E->getLocStart(),
5440                            /*IsStringLocation*/ false, SpecRange,
5441                            FixItHint::CreateReplacement(SpecRange, os.str()));
5442     } else {
5443       // The canonical type for formatting this value is different from the
5444       // actual type of the expression. (This occurs, for example, with Darwin's
5445       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5446       // should be printed as 'long' for 64-bit compatibility.)
5447       // Rather than emitting a normal format/argument mismatch, we want to
5448       // add a cast to the recommended type (and correct the format string
5449       // if necessary).
5450       SmallString<16> CastBuf;
5451       llvm::raw_svector_ostream CastFix(CastBuf);
5452       CastFix << "(";
5453       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5454       CastFix << ")";
5455
5456       SmallVector<FixItHint,4> Hints;
5457       if (!AT.matchesType(S.Context, IntendedTy))
5458         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5459
5460       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5461         // If there's already a cast present, just replace it.
5462         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5463         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5464
5465       } else if (!requiresParensToAddCast(E)) {
5466         // If the expression has high enough precedence,
5467         // just write the C-style cast.
5468         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5469                                                    CastFix.str()));
5470       } else {
5471         // Otherwise, add parens around the expression as well as the cast.
5472         CastFix << "(";
5473         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5474                                                    CastFix.str()));
5475
5476         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
5477         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5478       }
5479
5480       if (ShouldNotPrintDirectly) {
5481         // The expression has a type that should not be printed directly.
5482         // We extract the name from the typedef because we don't want to show
5483         // the underlying type in the diagnostic.
5484         StringRef Name;
5485         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5486           Name = TypedefTy->getDecl()->getName();
5487         else
5488           Name = CastTyName;
5489         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5490                                << Name << IntendedTy << IsEnum
5491                                << E->getSourceRange(),
5492                              E->getLocStart(), /*IsStringLocation=*/false,
5493                              SpecRange, Hints);
5494       } else {
5495         // In this case, the expression could be printed using a different
5496         // specifier, but we've decided that the specifier is probably correct 
5497         // and we should cast instead. Just use the normal warning message.
5498         EmitFormatDiagnostic(
5499           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5500             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5501             << E->getSourceRange(),
5502           E->getLocStart(), /*IsStringLocation*/false,
5503           SpecRange, Hints);
5504       }
5505     }
5506   } else {
5507     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5508                                                    SpecifierLen);
5509     // Since the warning for passing non-POD types to variadic functions
5510     // was deferred until now, we emit a warning for non-POD
5511     // arguments here.
5512     switch (S.isValidVarArgType(ExprTy)) {
5513     case Sema::VAK_Valid:
5514     case Sema::VAK_ValidInCXX11: {
5515       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5516       if (match == analyze_printf::ArgType::NoMatchPedantic) {
5517         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5518       }
5519
5520       EmitFormatDiagnostic(
5521           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5522                         << IsEnum << CSR << E->getSourceRange(),
5523           E->getLocStart(), /*IsStringLocation*/ false, CSR);
5524       break;
5525     }
5526     case Sema::VAK_Undefined:
5527     case Sema::VAK_MSVCUndefined:
5528       EmitFormatDiagnostic(
5529         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5530           << S.getLangOpts().CPlusPlus11
5531           << ExprTy
5532           << CallType
5533           << AT.getRepresentativeTypeName(S.Context)
5534           << CSR
5535           << E->getSourceRange(),
5536         E->getLocStart(), /*IsStringLocation*/false, CSR);
5537       checkForCStrMembers(AT, E);
5538       break;
5539
5540     case Sema::VAK_Invalid:
5541       if (ExprTy->isObjCObjectType())
5542         EmitFormatDiagnostic(
5543           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5544             << S.getLangOpts().CPlusPlus11
5545             << ExprTy
5546             << CallType
5547             << AT.getRepresentativeTypeName(S.Context)
5548             << CSR
5549             << E->getSourceRange(),
5550           E->getLocStart(), /*IsStringLocation*/false, CSR);
5551       else
5552         // FIXME: If this is an initializer list, suggest removing the braces
5553         // or inserting a cast to the target type.
5554         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5555           << isa<InitListExpr>(E) << ExprTy << CallType
5556           << AT.getRepresentativeTypeName(S.Context)
5557           << E->getSourceRange();
5558       break;
5559     }
5560
5561     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5562            "format string specifier index out of range");
5563     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
5564   }
5565
5566   return true;
5567 }
5568
5569 //===--- CHECK: Scanf format string checking ------------------------------===//
5570
5571 namespace {  
5572 class CheckScanfHandler : public CheckFormatHandler {
5573 public:
5574   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5575                     const Expr *origFormatExpr, unsigned firstDataArg,
5576                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
5577                     ArrayRef<const Expr *> Args,
5578                     unsigned formatIdx, bool inFunctionCall,
5579                     Sema::VariadicCallType CallType,
5580                     llvm::SmallBitVector &CheckedVarArgs,
5581                     UncoveredArgHandler &UncoveredArg)
5582     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5583                          numDataArgs, beg, hasVAListArg,
5584                          Args, formatIdx, inFunctionCall, CallType,
5585                          CheckedVarArgs, UncoveredArg)
5586   {}
5587   
5588   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5589                             const char *startSpecifier,
5590                             unsigned specifierLen) override;
5591   
5592   bool HandleInvalidScanfConversionSpecifier(
5593           const analyze_scanf::ScanfSpecifier &FS,
5594           const char *startSpecifier,
5595           unsigned specifierLen) override;
5596
5597   void HandleIncompleteScanList(const char *start, const char *end) override;
5598 };
5599 } // end anonymous namespace
5600
5601 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5602                                                  const char *end) {
5603   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5604                        getLocationOfByte(end), /*IsStringLocation*/true,
5605                        getSpecifierRange(start, end - start));
5606 }
5607
5608 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5609                                         const analyze_scanf::ScanfSpecifier &FS,
5610                                         const char *startSpecifier,
5611                                         unsigned specifierLen) {
5612
5613   const analyze_scanf::ScanfConversionSpecifier &CS =
5614     FS.getConversionSpecifier();
5615
5616   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5617                                           getLocationOfByte(CS.getStart()),
5618                                           startSpecifier, specifierLen,
5619                                           CS.getStart(), CS.getLength());
5620 }
5621
5622 bool CheckScanfHandler::HandleScanfSpecifier(
5623                                        const analyze_scanf::ScanfSpecifier &FS,
5624                                        const char *startSpecifier,
5625                                        unsigned specifierLen) {
5626   using namespace analyze_scanf;
5627   using namespace analyze_format_string;  
5628
5629   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
5630
5631   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
5632   // be used to decide if we are using positional arguments consistently.
5633   if (FS.consumesDataArgument()) {
5634     if (atFirstArg) {
5635       atFirstArg = false;
5636       usesPositionalArgs = FS.usesPositionalArg();
5637     }
5638     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5639       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5640                                         startSpecifier, specifierLen);
5641       return false;
5642     }
5643   }
5644   
5645   // Check if the field with is non-zero.
5646   const OptionalAmount &Amt = FS.getFieldWidth();
5647   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5648     if (Amt.getConstantAmount() == 0) {
5649       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5650                                                    Amt.getConstantLength());
5651       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5652                            getLocationOfByte(Amt.getStart()),
5653                            /*IsStringLocation*/true, R,
5654                            FixItHint::CreateRemoval(R));
5655     }
5656   }
5657
5658   if (!FS.consumesDataArgument()) {
5659     // FIXME: Technically specifying a precision or field width here
5660     // makes no sense.  Worth issuing a warning at some point.
5661     return true;
5662   }
5663
5664   // Consume the argument.
5665   unsigned argIndex = FS.getArgIndex();
5666   if (argIndex < NumDataArgs) {
5667       // The check to see if the argIndex is valid will come later.
5668       // We set the bit here because we may exit early from this
5669       // function if we encounter some other error.
5670     CoveredArgs.set(argIndex);
5671   }
5672
5673   // Check the length modifier is valid with the given conversion specifier.
5674   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5675     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5676                                 diag::warn_format_nonsensical_length);
5677   else if (!FS.hasStandardLengthModifier())
5678     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5679   else if (!FS.hasStandardLengthConversionCombination())
5680     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5681                                 diag::warn_format_non_standard_conversion_spec);
5682
5683   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5684     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5685
5686   // The remaining checks depend on the data arguments.
5687   if (HasVAListArg)
5688     return true;
5689
5690   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5691     return false;
5692
5693   // Check that the argument type matches the format specifier.
5694   const Expr *Ex = getDataArg(argIndex);
5695   if (!Ex)
5696     return true;
5697
5698   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
5699
5700   if (!AT.isValid()) {
5701     return true;
5702   }
5703
5704   analyze_format_string::ArgType::MatchKind match =
5705       AT.matchesType(S.Context, Ex->getType());
5706   if (match == analyze_format_string::ArgType::Match) {
5707     return true;
5708   }
5709
5710   ScanfSpecifier fixedFS = FS;
5711   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5712                                  S.getLangOpts(), S.Context);
5713
5714   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5715   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5716     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5717   }
5718
5719   if (success) {
5720     // Get the fix string from the fixed format specifier.
5721     SmallString<128> buf;
5722     llvm::raw_svector_ostream os(buf);
5723     fixedFS.toString(os);
5724
5725     EmitFormatDiagnostic(
5726         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5727                       << Ex->getType() << false << Ex->getSourceRange(),
5728         Ex->getLocStart(),
5729         /*IsStringLocation*/ false,
5730         getSpecifierRange(startSpecifier, specifierLen),
5731         FixItHint::CreateReplacement(
5732             getSpecifierRange(startSpecifier, specifierLen), os.str()));
5733   } else {
5734     EmitFormatDiagnostic(S.PDiag(diag)
5735                              << AT.getRepresentativeTypeName(S.Context)
5736                              << Ex->getType() << false << Ex->getSourceRange(),
5737                          Ex->getLocStart(),
5738                          /*IsStringLocation*/ false,
5739                          getSpecifierRange(startSpecifier, specifierLen));
5740   }
5741
5742   return true;
5743 }
5744
5745 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5746                               const Expr *OrigFormatExpr,
5747                               ArrayRef<const Expr *> Args,
5748                               bool HasVAListArg, unsigned format_idx,
5749                               unsigned firstDataArg,
5750                               Sema::FormatStringType Type,
5751                               bool inFunctionCall,
5752                               Sema::VariadicCallType CallType,
5753                               llvm::SmallBitVector &CheckedVarArgs,
5754                               UncoveredArgHandler &UncoveredArg) {
5755   // CHECK: is the format string a wide literal?
5756   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
5757     CheckFormatHandler::EmitFormatDiagnostic(
5758       S, inFunctionCall, Args[format_idx],
5759       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
5760       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5761     return;
5762   }
5763
5764   // Str - The format string.  NOTE: this is NOT null-terminated!
5765   StringRef StrRef = FExpr->getString();
5766   const char *Str = StrRef.data();
5767   // Account for cases where the string literal is truncated in a declaration.
5768   const ConstantArrayType *T =
5769     S.Context.getAsConstantArrayType(FExpr->getType());
5770   assert(T && "String literal not of constant array type!");
5771   size_t TypeSize = T->getSize().getZExtValue();
5772   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5773   const unsigned numDataArgs = Args.size() - firstDataArg;
5774
5775   // Emit a warning if the string literal is truncated and does not contain an
5776   // embedded null character.
5777   if (TypeSize <= StrRef.size() &&
5778       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5779     CheckFormatHandler::EmitFormatDiagnostic(
5780         S, inFunctionCall, Args[format_idx],
5781         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
5782         FExpr->getLocStart(),
5783         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5784     return;
5785   }
5786
5787   // CHECK: empty format string?
5788   if (StrLen == 0 && numDataArgs > 0) {
5789     CheckFormatHandler::EmitFormatDiagnostic(
5790       S, inFunctionCall, Args[format_idx],
5791       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
5792       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5793     return;
5794   }
5795
5796   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5797       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5798     CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5799                          numDataArgs, (Type == Sema::FST_NSString ||
5800                                        Type == Sema::FST_OSTrace),
5801                          Str, HasVAListArg, Args, format_idx,
5802                          inFunctionCall, CallType, CheckedVarArgs,
5803                          UncoveredArg);
5804
5805     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
5806                                                   S.getLangOpts(),
5807                                                   S.Context.getTargetInfo(),
5808                                             Type == Sema::FST_FreeBSDKPrintf))
5809       H.DoneProcessing();
5810   } else if (Type == Sema::FST_Scanf) {
5811     CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5812                         Str, HasVAListArg, Args, format_idx,
5813                         inFunctionCall, CallType, CheckedVarArgs,
5814                         UncoveredArg);
5815
5816     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
5817                                                  S.getLangOpts(),
5818                                                  S.Context.getTargetInfo()))
5819       H.DoneProcessing();
5820   } // TODO: handle other formats
5821 }
5822
5823 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5824   // Str - The format string.  NOTE: this is NOT null-terminated!
5825   StringRef StrRef = FExpr->getString();
5826   const char *Str = StrRef.data();
5827   // Account for cases where the string literal is truncated in a declaration.
5828   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5829   assert(T && "String literal not of constant array type!");
5830   size_t TypeSize = T->getSize().getZExtValue();
5831   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5832   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5833                                                          getLangOpts(),
5834                                                          Context.getTargetInfo());
5835 }
5836
5837 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5838
5839 // Returns the related absolute value function that is larger, of 0 if one
5840 // does not exist.
5841 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5842   switch (AbsFunction) {
5843   default:
5844     return 0;
5845
5846   case Builtin::BI__builtin_abs:
5847     return Builtin::BI__builtin_labs;
5848   case Builtin::BI__builtin_labs:
5849     return Builtin::BI__builtin_llabs;
5850   case Builtin::BI__builtin_llabs:
5851     return 0;
5852
5853   case Builtin::BI__builtin_fabsf:
5854     return Builtin::BI__builtin_fabs;
5855   case Builtin::BI__builtin_fabs:
5856     return Builtin::BI__builtin_fabsl;
5857   case Builtin::BI__builtin_fabsl:
5858     return 0;
5859
5860   case Builtin::BI__builtin_cabsf:
5861     return Builtin::BI__builtin_cabs;
5862   case Builtin::BI__builtin_cabs:
5863     return Builtin::BI__builtin_cabsl;
5864   case Builtin::BI__builtin_cabsl:
5865     return 0;
5866
5867   case Builtin::BIabs:
5868     return Builtin::BIlabs;
5869   case Builtin::BIlabs:
5870     return Builtin::BIllabs;
5871   case Builtin::BIllabs:
5872     return 0;
5873
5874   case Builtin::BIfabsf:
5875     return Builtin::BIfabs;
5876   case Builtin::BIfabs:
5877     return Builtin::BIfabsl;
5878   case Builtin::BIfabsl:
5879     return 0;
5880
5881   case Builtin::BIcabsf:
5882    return Builtin::BIcabs;
5883   case Builtin::BIcabs:
5884     return Builtin::BIcabsl;
5885   case Builtin::BIcabsl:
5886     return 0;
5887   }
5888 }
5889
5890 // Returns the argument type of the absolute value function.
5891 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5892                                              unsigned AbsType) {
5893   if (AbsType == 0)
5894     return QualType();
5895
5896   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5897   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5898   if (Error != ASTContext::GE_None)
5899     return QualType();
5900
5901   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5902   if (!FT)
5903     return QualType();
5904
5905   if (FT->getNumParams() != 1)
5906     return QualType();
5907
5908   return FT->getParamType(0);
5909 }
5910
5911 // Returns the best absolute value function, or zero, based on type and
5912 // current absolute value function.
5913 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5914                                    unsigned AbsFunctionKind) {
5915   unsigned BestKind = 0;
5916   uint64_t ArgSize = Context.getTypeSize(ArgType);
5917   for (unsigned Kind = AbsFunctionKind; Kind != 0;
5918        Kind = getLargerAbsoluteValueFunction(Kind)) {
5919     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5920     if (Context.getTypeSize(ParamType) >= ArgSize) {
5921       if (BestKind == 0)
5922         BestKind = Kind;
5923       else if (Context.hasSameType(ParamType, ArgType)) {
5924         BestKind = Kind;
5925         break;
5926       }
5927     }
5928   }
5929   return BestKind;
5930 }
5931
5932 enum AbsoluteValueKind {
5933   AVK_Integer,
5934   AVK_Floating,
5935   AVK_Complex
5936 };
5937
5938 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5939   if (T->isIntegralOrEnumerationType())
5940     return AVK_Integer;
5941   if (T->isRealFloatingType())
5942     return AVK_Floating;
5943   if (T->isAnyComplexType())
5944     return AVK_Complex;
5945
5946   llvm_unreachable("Type not integer, floating, or complex");
5947 }
5948
5949 // Changes the absolute value function to a different type.  Preserves whether
5950 // the function is a builtin.
5951 static unsigned changeAbsFunction(unsigned AbsKind,
5952                                   AbsoluteValueKind ValueKind) {
5953   switch (ValueKind) {
5954   case AVK_Integer:
5955     switch (AbsKind) {
5956     default:
5957       return 0;
5958     case Builtin::BI__builtin_fabsf:
5959     case Builtin::BI__builtin_fabs:
5960     case Builtin::BI__builtin_fabsl:
5961     case Builtin::BI__builtin_cabsf:
5962     case Builtin::BI__builtin_cabs:
5963     case Builtin::BI__builtin_cabsl:
5964       return Builtin::BI__builtin_abs;
5965     case Builtin::BIfabsf:
5966     case Builtin::BIfabs:
5967     case Builtin::BIfabsl:
5968     case Builtin::BIcabsf:
5969     case Builtin::BIcabs:
5970     case Builtin::BIcabsl:
5971       return Builtin::BIabs;
5972     }
5973   case AVK_Floating:
5974     switch (AbsKind) {
5975     default:
5976       return 0;
5977     case Builtin::BI__builtin_abs:
5978     case Builtin::BI__builtin_labs:
5979     case Builtin::BI__builtin_llabs:
5980     case Builtin::BI__builtin_cabsf:
5981     case Builtin::BI__builtin_cabs:
5982     case Builtin::BI__builtin_cabsl:
5983       return Builtin::BI__builtin_fabsf;
5984     case Builtin::BIabs:
5985     case Builtin::BIlabs:
5986     case Builtin::BIllabs:
5987     case Builtin::BIcabsf:
5988     case Builtin::BIcabs:
5989     case Builtin::BIcabsl:
5990       return Builtin::BIfabsf;
5991     }
5992   case AVK_Complex:
5993     switch (AbsKind) {
5994     default:
5995       return 0;
5996     case Builtin::BI__builtin_abs:
5997     case Builtin::BI__builtin_labs:
5998     case Builtin::BI__builtin_llabs:
5999     case Builtin::BI__builtin_fabsf:
6000     case Builtin::BI__builtin_fabs:
6001     case Builtin::BI__builtin_fabsl:
6002       return Builtin::BI__builtin_cabsf;
6003     case Builtin::BIabs:
6004     case Builtin::BIlabs:
6005     case Builtin::BIllabs:
6006     case Builtin::BIfabsf:
6007     case Builtin::BIfabs:
6008     case Builtin::BIfabsl:
6009       return Builtin::BIcabsf;
6010     }
6011   }
6012   llvm_unreachable("Unable to convert function");
6013 }
6014
6015 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6016   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6017   if (!FnInfo)
6018     return 0;
6019
6020   switch (FDecl->getBuiltinID()) {
6021   default:
6022     return 0;
6023   case Builtin::BI__builtin_abs:
6024   case Builtin::BI__builtin_fabs:
6025   case Builtin::BI__builtin_fabsf:
6026   case Builtin::BI__builtin_fabsl:
6027   case Builtin::BI__builtin_labs:
6028   case Builtin::BI__builtin_llabs:
6029   case Builtin::BI__builtin_cabs:
6030   case Builtin::BI__builtin_cabsf:
6031   case Builtin::BI__builtin_cabsl:
6032   case Builtin::BIabs:
6033   case Builtin::BIlabs:
6034   case Builtin::BIllabs:
6035   case Builtin::BIfabs:
6036   case Builtin::BIfabsf:
6037   case Builtin::BIfabsl:
6038   case Builtin::BIcabs:
6039   case Builtin::BIcabsf:
6040   case Builtin::BIcabsl:
6041     return FDecl->getBuiltinID();
6042   }
6043   llvm_unreachable("Unknown Builtin type");
6044 }
6045
6046 // If the replacement is valid, emit a note with replacement function.
6047 // Additionally, suggest including the proper header if not already included.
6048 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6049                             unsigned AbsKind, QualType ArgType) {
6050   bool EmitHeaderHint = true;
6051   const char *HeaderName = nullptr;
6052   const char *FunctionName = nullptr;
6053   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6054     FunctionName = "std::abs";
6055     if (ArgType->isIntegralOrEnumerationType()) {
6056       HeaderName = "cstdlib";
6057     } else if (ArgType->isRealFloatingType()) {
6058       HeaderName = "cmath";
6059     } else {
6060       llvm_unreachable("Invalid Type");
6061     }
6062
6063     // Lookup all std::abs
6064     if (NamespaceDecl *Std = S.getStdNamespace()) {
6065       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6066       R.suppressDiagnostics();
6067       S.LookupQualifiedName(R, Std);
6068
6069       for (const auto *I : R) {
6070         const FunctionDecl *FDecl = nullptr;
6071         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6072           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6073         } else {
6074           FDecl = dyn_cast<FunctionDecl>(I);
6075         }
6076         if (!FDecl)
6077           continue;
6078
6079         // Found std::abs(), check that they are the right ones.
6080         if (FDecl->getNumParams() != 1)
6081           continue;
6082
6083         // Check that the parameter type can handle the argument.
6084         QualType ParamType = FDecl->getParamDecl(0)->getType();
6085         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6086             S.Context.getTypeSize(ArgType) <=
6087                 S.Context.getTypeSize(ParamType)) {
6088           // Found a function, don't need the header hint.
6089           EmitHeaderHint = false;
6090           break;
6091         }
6092       }
6093     }
6094   } else {
6095     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6096     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6097
6098     if (HeaderName) {
6099       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6100       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6101       R.suppressDiagnostics();
6102       S.LookupName(R, S.getCurScope());
6103
6104       if (R.isSingleResult()) {
6105         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6106         if (FD && FD->getBuiltinID() == AbsKind) {
6107           EmitHeaderHint = false;
6108         } else {
6109           return;
6110         }
6111       } else if (!R.empty()) {
6112         return;
6113       }
6114     }
6115   }
6116
6117   S.Diag(Loc, diag::note_replace_abs_function)
6118       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6119
6120   if (!HeaderName)
6121     return;
6122
6123   if (!EmitHeaderHint)
6124     return;
6125
6126   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6127                                                     << FunctionName;
6128 }
6129
6130 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6131   if (!FDecl)
6132     return false;
6133
6134   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6135     return false;
6136
6137   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6138
6139   while (ND && ND->isInlineNamespace()) {
6140     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
6141   }
6142
6143   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6144     return false;
6145
6146   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6147     return false;
6148
6149   return true;
6150 }
6151
6152 // Warn when using the wrong abs() function.
6153 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6154                                       const FunctionDecl *FDecl,
6155                                       IdentifierInfo *FnInfo) {
6156   if (Call->getNumArgs() != 1)
6157     return;
6158
6159   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6160   bool IsStdAbs = IsFunctionStdAbs(FDecl);
6161   if (AbsKind == 0 && !IsStdAbs)
6162     return;
6163
6164   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6165   QualType ParamType = Call->getArg(0)->getType();
6166
6167   // Unsigned types cannot be negative.  Suggest removing the absolute value
6168   // function call.
6169   if (ArgType->isUnsignedIntegerType()) {
6170     const char *FunctionName =
6171         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6172     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6173     Diag(Call->getExprLoc(), diag::note_remove_abs)
6174         << FunctionName
6175         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6176     return;
6177   }
6178
6179   // Taking the absolute value of a pointer is very suspicious, they probably
6180   // wanted to index into an array, dereference a pointer, call a function, etc.
6181   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6182     unsigned DiagType = 0;
6183     if (ArgType->isFunctionType())
6184       DiagType = 1;
6185     else if (ArgType->isArrayType())
6186       DiagType = 2;
6187
6188     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6189     return;
6190   }
6191
6192   // std::abs has overloads which prevent most of the absolute value problems
6193   // from occurring.
6194   if (IsStdAbs)
6195     return;
6196
6197   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6198   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6199
6200   // The argument and parameter are the same kind.  Check if they are the right
6201   // size.
6202   if (ArgValueKind == ParamValueKind) {
6203     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6204       return;
6205
6206     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6207     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6208         << FDecl << ArgType << ParamType;
6209
6210     if (NewAbsKind == 0)
6211       return;
6212
6213     emitReplacement(*this, Call->getExprLoc(),
6214                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6215     return;
6216   }
6217
6218   // ArgValueKind != ParamValueKind
6219   // The wrong type of absolute value function was used.  Attempt to find the
6220   // proper one.
6221   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6222   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6223   if (NewAbsKind == 0)
6224     return;
6225
6226   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6227       << FDecl << ParamValueKind << ArgValueKind;
6228
6229   emitReplacement(*this, Call->getExprLoc(),
6230                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6231 }
6232
6233 //===--- CHECK: Standard memory functions ---------------------------------===//
6234
6235 /// \brief Takes the expression passed to the size_t parameter of functions
6236 /// such as memcmp, strncat, etc and warns if it's a comparison.
6237 ///
6238 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6239 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6240                                            IdentifierInfo *FnName,
6241                                            SourceLocation FnLoc,
6242                                            SourceLocation RParenLoc) {
6243   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6244   if (!Size)
6245     return false;
6246
6247   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6248   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6249     return false;
6250
6251   SourceRange SizeRange = Size->getSourceRange();
6252   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6253       << SizeRange << FnName;
6254   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6255       << FnName << FixItHint::CreateInsertion(
6256                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6257       << FixItHint::CreateRemoval(RParenLoc);
6258   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6259       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6260       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6261                                     ")");
6262
6263   return true;
6264 }
6265
6266 /// \brief Determine whether the given type is or contains a dynamic class type
6267 /// (e.g., whether it has a vtable).
6268 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6269                                                      bool &IsContained) {
6270   // Look through array types while ignoring qualifiers.
6271   const Type *Ty = T->getBaseElementTypeUnsafe();
6272   IsContained = false;
6273
6274   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6275   RD = RD ? RD->getDefinition() : nullptr;
6276   if (!RD || RD->isInvalidDecl())
6277     return nullptr;
6278
6279   if (RD->isDynamicClass())
6280     return RD;
6281
6282   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6283   // It's impossible for a class to transitively contain itself by value, so
6284   // infinite recursion is impossible.
6285   for (auto *FD : RD->fields()) {
6286     bool SubContained;
6287     if (const CXXRecordDecl *ContainedRD =
6288             getContainedDynamicClass(FD->getType(), SubContained)) {
6289       IsContained = true;
6290       return ContainedRD;
6291     }
6292   }
6293
6294   return nullptr;
6295 }
6296
6297 /// \brief If E is a sizeof expression, returns its argument expression,
6298 /// otherwise returns NULL.
6299 static const Expr *getSizeOfExprArg(const Expr *E) {
6300   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6301       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6302     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6303       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6304
6305   return nullptr;
6306 }
6307
6308 /// \brief If E is a sizeof expression, returns its argument type.
6309 static QualType getSizeOfArgType(const Expr *E) {
6310   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6311       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6312     if (SizeOf->getKind() == clang::UETT_SizeOf)
6313       return SizeOf->getTypeOfArgument();
6314
6315   return QualType();
6316 }
6317
6318 /// \brief Check for dangerous or invalid arguments to memset().
6319 ///
6320 /// This issues warnings on known problematic, dangerous or unspecified
6321 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6322 /// function calls.
6323 ///
6324 /// \param Call The call expression to diagnose.
6325 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6326                                    unsigned BId,
6327                                    IdentifierInfo *FnName) {
6328   assert(BId != 0);
6329
6330   // It is possible to have a non-standard definition of memset.  Validate
6331   // we have enough arguments, and if not, abort further checking.
6332   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
6333   if (Call->getNumArgs() < ExpectedNumArgs)
6334     return;
6335
6336   unsigned LastArg = (BId == Builtin::BImemset ||
6337                       BId == Builtin::BIstrndup ? 1 : 2);
6338   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
6339   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6340
6341   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6342                                      Call->getLocStart(), Call->getRParenLoc()))
6343     return;
6344
6345   // We have special checking when the length is a sizeof expression.
6346   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6347   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6348   llvm::FoldingSetNodeID SizeOfArgID;
6349
6350   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6351     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6352     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6353
6354     QualType DestTy = Dest->getType();
6355     QualType PointeeTy;
6356     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6357       PointeeTy = DestPtrTy->getPointeeType();
6358
6359       // Never warn about void type pointers. This can be used to suppress
6360       // false positives.
6361       if (PointeeTy->isVoidType())
6362         continue;
6363
6364       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6365       // actually comparing the expressions for equality. Because computing the
6366       // expression IDs can be expensive, we only do this if the diagnostic is
6367       // enabled.
6368       if (SizeOfArg &&
6369           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6370                            SizeOfArg->getExprLoc())) {
6371         // We only compute IDs for expressions if the warning is enabled, and
6372         // cache the sizeof arg's ID.
6373         if (SizeOfArgID == llvm::FoldingSetNodeID())
6374           SizeOfArg->Profile(SizeOfArgID, Context, true);
6375         llvm::FoldingSetNodeID DestID;
6376         Dest->Profile(DestID, Context, true);
6377         if (DestID == SizeOfArgID) {
6378           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6379           //       over sizeof(src) as well.
6380           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6381           StringRef ReadableName = FnName->getName();
6382
6383           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6384             if (UnaryOp->getOpcode() == UO_AddrOf)
6385               ActionIdx = 1; // If its an address-of operator, just remove it.
6386           if (!PointeeTy->isIncompleteType() &&
6387               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6388             ActionIdx = 2; // If the pointee's size is sizeof(char),
6389                            // suggest an explicit length.
6390
6391           // If the function is defined as a builtin macro, do not show macro
6392           // expansion.
6393           SourceLocation SL = SizeOfArg->getExprLoc();
6394           SourceRange DSR = Dest->getSourceRange();
6395           SourceRange SSR = SizeOfArg->getSourceRange();
6396           SourceManager &SM = getSourceManager();
6397
6398           if (SM.isMacroArgExpansion(SL)) {
6399             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6400             SL = SM.getSpellingLoc(SL);
6401             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6402                              SM.getSpellingLoc(DSR.getEnd()));
6403             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6404                              SM.getSpellingLoc(SSR.getEnd()));
6405           }
6406
6407           DiagRuntimeBehavior(SL, SizeOfArg,
6408                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6409                                 << ReadableName
6410                                 << PointeeTy
6411                                 << DestTy
6412                                 << DSR
6413                                 << SSR);
6414           DiagRuntimeBehavior(SL, SizeOfArg,
6415                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6416                                 << ActionIdx
6417                                 << SSR);
6418
6419           break;
6420         }
6421       }
6422
6423       // Also check for cases where the sizeof argument is the exact same
6424       // type as the memory argument, and where it points to a user-defined
6425       // record type.
6426       if (SizeOfArgTy != QualType()) {
6427         if (PointeeTy->isRecordType() &&
6428             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6429           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6430                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6431                                 << FnName << SizeOfArgTy << ArgIdx
6432                                 << PointeeTy << Dest->getSourceRange()
6433                                 << LenExpr->getSourceRange());
6434           break;
6435         }
6436       }
6437     } else if (DestTy->isArrayType()) {
6438       PointeeTy = DestTy;
6439     }
6440
6441     if (PointeeTy == QualType())
6442       continue;
6443
6444     // Always complain about dynamic classes.
6445     bool IsContained;
6446     if (const CXXRecordDecl *ContainedRD =
6447             getContainedDynamicClass(PointeeTy, IsContained)) {
6448
6449       unsigned OperationType = 0;
6450       // "overwritten" if we're warning about the destination for any call
6451       // but memcmp; otherwise a verb appropriate to the call.
6452       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6453         if (BId == Builtin::BImemcpy)
6454           OperationType = 1;
6455         else if(BId == Builtin::BImemmove)
6456           OperationType = 2;
6457         else if (BId == Builtin::BImemcmp)
6458           OperationType = 3;
6459       }
6460         
6461       DiagRuntimeBehavior(
6462         Dest->getExprLoc(), Dest,
6463         PDiag(diag::warn_dyn_class_memaccess)
6464           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6465           << FnName << IsContained << ContainedRD << OperationType
6466           << Call->getCallee()->getSourceRange());
6467     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6468              BId != Builtin::BImemset)
6469       DiagRuntimeBehavior(
6470         Dest->getExprLoc(), Dest,
6471         PDiag(diag::warn_arc_object_memaccess)
6472           << ArgIdx << FnName << PointeeTy
6473           << Call->getCallee()->getSourceRange());
6474     else
6475       continue;
6476
6477     DiagRuntimeBehavior(
6478       Dest->getExprLoc(), Dest,
6479       PDiag(diag::note_bad_memaccess_silence)
6480         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6481     break;
6482   }
6483 }
6484
6485 // A little helper routine: ignore addition and subtraction of integer literals.
6486 // This intentionally does not ignore all integer constant expressions because
6487 // we don't want to remove sizeof().
6488 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6489   Ex = Ex->IgnoreParenCasts();
6490
6491   for (;;) {
6492     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6493     if (!BO || !BO->isAdditiveOp())
6494       break;
6495
6496     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6497     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6498     
6499     if (isa<IntegerLiteral>(RHS))
6500       Ex = LHS;
6501     else if (isa<IntegerLiteral>(LHS))
6502       Ex = RHS;
6503     else
6504       break;
6505   }
6506
6507   return Ex;
6508 }
6509
6510 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6511                                                       ASTContext &Context) {
6512   // Only handle constant-sized or VLAs, but not flexible members.
6513   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6514     // Only issue the FIXIT for arrays of size > 1.
6515     if (CAT->getSize().getSExtValue() <= 1)
6516       return false;
6517   } else if (!Ty->isVariableArrayType()) {
6518     return false;
6519   }
6520   return true;
6521 }
6522
6523 // Warn if the user has made the 'size' argument to strlcpy or strlcat
6524 // be the size of the source, instead of the destination.
6525 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6526                                     IdentifierInfo *FnName) {
6527
6528   // Don't crash if the user has the wrong number of arguments
6529   unsigned NumArgs = Call->getNumArgs();
6530   if ((NumArgs != 3) && (NumArgs != 4))
6531     return;
6532
6533   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6534   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
6535   const Expr *CompareWithSrc = nullptr;
6536
6537   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6538                                      Call->getLocStart(), Call->getRParenLoc()))
6539     return;
6540   
6541   // Look for 'strlcpy(dst, x, sizeof(x))'
6542   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6543     CompareWithSrc = Ex;
6544   else {
6545     // Look for 'strlcpy(dst, x, strlen(x))'
6546     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6547       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6548           SizeCall->getNumArgs() == 1)
6549         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6550     }
6551   }
6552
6553   if (!CompareWithSrc)
6554     return;
6555
6556   // Determine if the argument to sizeof/strlen is equal to the source
6557   // argument.  In principle there's all kinds of things you could do
6558   // here, for instance creating an == expression and evaluating it with
6559   // EvaluateAsBooleanCondition, but this uses a more direct technique:
6560   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6561   if (!SrcArgDRE)
6562     return;
6563   
6564   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6565   if (!CompareWithSrcDRE || 
6566       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6567     return;
6568   
6569   const Expr *OriginalSizeArg = Call->getArg(2);
6570   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6571     << OriginalSizeArg->getSourceRange() << FnName;
6572   
6573   // Output a FIXIT hint if the destination is an array (rather than a
6574   // pointer to an array).  This could be enhanced to handle some
6575   // pointers if we know the actual size, like if DstArg is 'array+2'
6576   // we could say 'sizeof(array)-2'.
6577   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
6578   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
6579     return;
6580
6581   SmallString<128> sizeString;
6582   llvm::raw_svector_ostream OS(sizeString);
6583   OS << "sizeof(";
6584   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6585   OS << ")";
6586   
6587   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6588     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6589                                     OS.str());
6590 }
6591
6592 /// Check if two expressions refer to the same declaration.
6593 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6594   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6595     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6596       return D1->getDecl() == D2->getDecl();
6597   return false;
6598 }
6599
6600 static const Expr *getStrlenExprArg(const Expr *E) {
6601   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6602     const FunctionDecl *FD = CE->getDirectCallee();
6603     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
6604       return nullptr;
6605     return CE->getArg(0)->IgnoreParenCasts();
6606   }
6607   return nullptr;
6608 }
6609
6610 // Warn on anti-patterns as the 'size' argument to strncat.
6611 // The correct size argument should look like following:
6612 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6613 void Sema::CheckStrncatArguments(const CallExpr *CE,
6614                                  IdentifierInfo *FnName) {
6615   // Don't crash if the user has the wrong number of arguments.
6616   if (CE->getNumArgs() < 3)
6617     return;
6618   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6619   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6620   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6621
6622   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6623                                      CE->getRParenLoc()))
6624     return;
6625
6626   // Identify common expressions, which are wrongly used as the size argument
6627   // to strncat and may lead to buffer overflows.
6628   unsigned PatternType = 0;
6629   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6630     // - sizeof(dst)
6631     if (referToTheSameDecl(SizeOfArg, DstArg))
6632       PatternType = 1;
6633     // - sizeof(src)
6634     else if (referToTheSameDecl(SizeOfArg, SrcArg))
6635       PatternType = 2;
6636   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6637     if (BE->getOpcode() == BO_Sub) {
6638       const Expr *L = BE->getLHS()->IgnoreParenCasts();
6639       const Expr *R = BE->getRHS()->IgnoreParenCasts();
6640       // - sizeof(dst) - strlen(dst)
6641       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6642           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6643         PatternType = 1;
6644       // - sizeof(src) - (anything)
6645       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6646         PatternType = 2;
6647     }
6648   }
6649
6650   if (PatternType == 0)
6651     return;
6652
6653   // Generate the diagnostic.
6654   SourceLocation SL = LenArg->getLocStart();
6655   SourceRange SR = LenArg->getSourceRange();
6656   SourceManager &SM = getSourceManager();
6657
6658   // If the function is defined as a builtin macro, do not show macro expansion.
6659   if (SM.isMacroArgExpansion(SL)) {
6660     SL = SM.getSpellingLoc(SL);
6661     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6662                      SM.getSpellingLoc(SR.getEnd()));
6663   }
6664
6665   // Check if the destination is an array (rather than a pointer to an array).
6666   QualType DstTy = DstArg->getType();
6667   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6668                                                                     Context);
6669   if (!isKnownSizeArray) {
6670     if (PatternType == 1)
6671       Diag(SL, diag::warn_strncat_wrong_size) << SR;
6672     else
6673       Diag(SL, diag::warn_strncat_src_size) << SR;
6674     return;
6675   }
6676
6677   if (PatternType == 1)
6678     Diag(SL, diag::warn_strncat_large_size) << SR;
6679   else
6680     Diag(SL, diag::warn_strncat_src_size) << SR;
6681
6682   SmallString<128> sizeString;
6683   llvm::raw_svector_ostream OS(sizeString);
6684   OS << "sizeof(";
6685   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6686   OS << ") - ";
6687   OS << "strlen(";
6688   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6689   OS << ") - 1";
6690
6691   Diag(SL, diag::note_strncat_wrong_size)
6692     << FixItHint::CreateReplacement(SR, OS.str());
6693 }
6694
6695 //===--- CHECK: Return Address of Stack Variable --------------------------===//
6696
6697 static const Expr *EvalVal(const Expr *E,
6698                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6699                            const Decl *ParentDecl);
6700 static const Expr *EvalAddr(const Expr *E,
6701                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6702                             const Decl *ParentDecl);
6703
6704 /// CheckReturnStackAddr - Check if a return statement returns the address
6705 ///   of a stack variable.
6706 static void
6707 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6708                      SourceLocation ReturnLoc) {
6709
6710   const Expr *stackE = nullptr;
6711   SmallVector<const DeclRefExpr *, 8> refVars;
6712
6713   // Perform checking for returned stack addresses, local blocks,
6714   // label addresses or references to temporaries.
6715   if (lhsType->isPointerType() ||
6716       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
6717     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
6718   } else if (lhsType->isReferenceType()) {
6719     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
6720   }
6721
6722   if (!stackE)
6723     return; // Nothing suspicious was found.
6724
6725   // Parameters are initalized in the calling scope, so taking the address
6726   // of a parameter reference doesn't need a warning.
6727   for (auto *DRE : refVars)
6728     if (isa<ParmVarDecl>(DRE->getDecl()))
6729       return;
6730
6731   SourceLocation diagLoc;
6732   SourceRange diagRange;
6733   if (refVars.empty()) {
6734     diagLoc = stackE->getLocStart();
6735     diagRange = stackE->getSourceRange();
6736   } else {
6737     // We followed through a reference variable. 'stackE' contains the
6738     // problematic expression but we will warn at the return statement pointing
6739     // at the reference variable. We will later display the "trail" of
6740     // reference variables using notes.
6741     diagLoc = refVars[0]->getLocStart();
6742     diagRange = refVars[0]->getSourceRange();
6743   }
6744
6745   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6746     // address of local var
6747     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
6748      << DR->getDecl()->getDeclName() << diagRange;
6749   } else if (isa<BlockExpr>(stackE)) { // local block.
6750     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6751   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
6752     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6753   } else { // local temporary.
6754     // If there is an LValue->RValue conversion, then the value of the
6755     // reference type is used, not the reference.
6756     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6757       if (ICE->getCastKind() == CK_LValueToRValue) {
6758         return;
6759       }
6760     }
6761     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6762      << lhsType->isReferenceType() << diagRange;
6763   }
6764
6765   // Display the "trail" of reference variables that we followed until we
6766   // found the problematic expression using notes.
6767   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
6768     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6769     // If this var binds to another reference var, show the range of the next
6770     // var, otherwise the var binds to the problematic expression, in which case
6771     // show the range of the expression.
6772     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6773                                     : stackE->getSourceRange();
6774     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6775         << VD->getDeclName() << range;
6776   }
6777 }
6778
6779 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6780 ///  check if the expression in a return statement evaluates to an address
6781 ///  to a location on the stack, a local block, an address of a label, or a
6782 ///  reference to local temporary. The recursion is used to traverse the
6783 ///  AST of the return expression, with recursion backtracking when we
6784 ///  encounter a subexpression that (1) clearly does not lead to one of the
6785 ///  above problematic expressions (2) is something we cannot determine leads to
6786 ///  a problematic expression based on such local checking.
6787 ///
6788 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
6789 ///  the expression that they point to. Such variables are added to the
6790 ///  'refVars' vector so that we know what the reference variable "trail" was.
6791 ///
6792 ///  EvalAddr processes expressions that are pointers that are used as
6793 ///  references (and not L-values).  EvalVal handles all other values.
6794 ///  At the base case of the recursion is a check for the above problematic
6795 ///  expressions.
6796 ///
6797 ///  This implementation handles:
6798 ///
6799 ///   * pointer-to-pointer casts
6800 ///   * implicit conversions from array references to pointers
6801 ///   * taking the address of fields
6802 ///   * arbitrary interplay between "&" and "*" operators
6803 ///   * pointer arithmetic from an address of a stack variable
6804 ///   * taking the address of an array element where the array is on the stack
6805 static const Expr *EvalAddr(const Expr *E,
6806                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6807                             const Decl *ParentDecl) {
6808   if (E->isTypeDependent())
6809     return nullptr;
6810
6811   // We should only be called for evaluating pointer expressions.
6812   assert((E->getType()->isAnyPointerType() ||
6813           E->getType()->isBlockPointerType() ||
6814           E->getType()->isObjCQualifiedIdType()) &&
6815          "EvalAddr only works on pointers");
6816
6817   E = E->IgnoreParens();
6818
6819   // Our "symbolic interpreter" is just a dispatch off the currently
6820   // viewed AST node.  We then recursively traverse the AST by calling
6821   // EvalAddr and EvalVal appropriately.
6822   switch (E->getStmtClass()) {
6823   case Stmt::DeclRefExprClass: {
6824     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6825
6826     // If we leave the immediate function, the lifetime isn't about to end.
6827     if (DR->refersToEnclosingVariableOrCapture())
6828       return nullptr;
6829
6830     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
6831       // If this is a reference variable, follow through to the expression that
6832       // it points to.
6833       if (V->hasLocalStorage() &&
6834           V->getType()->isReferenceType() && V->hasInit()) {
6835         // Add the reference variable to the "trail".
6836         refVars.push_back(DR);
6837         return EvalAddr(V->getInit(), refVars, ParentDecl);
6838       }
6839
6840     return nullptr;
6841   }
6842
6843   case Stmt::UnaryOperatorClass: {
6844     // The only unary operator that make sense to handle here
6845     // is AddrOf.  All others don't make sense as pointers.
6846     const UnaryOperator *U = cast<UnaryOperator>(E);
6847
6848     if (U->getOpcode() == UO_AddrOf)
6849       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
6850     return nullptr;
6851   }
6852
6853   case Stmt::BinaryOperatorClass: {
6854     // Handle pointer arithmetic.  All other binary operators are not valid
6855     // in this context.
6856     const BinaryOperator *B = cast<BinaryOperator>(E);
6857     BinaryOperatorKind op = B->getOpcode();
6858
6859     if (op != BO_Add && op != BO_Sub)
6860       return nullptr;
6861
6862     const Expr *Base = B->getLHS();
6863
6864     // Determine which argument is the real pointer base.  It could be
6865     // the RHS argument instead of the LHS.
6866     if (!Base->getType()->isPointerType())
6867       Base = B->getRHS();
6868
6869     assert(Base->getType()->isPointerType());
6870     return EvalAddr(Base, refVars, ParentDecl);
6871   }
6872
6873   // For conditional operators we need to see if either the LHS or RHS are
6874   // valid DeclRefExpr*s.  If one of them is valid, we return it.
6875   case Stmt::ConditionalOperatorClass: {
6876     const ConditionalOperator *C = cast<ConditionalOperator>(E);
6877
6878     // Handle the GNU extension for missing LHS.
6879     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
6880     if (const Expr *LHSExpr = C->getLHS()) {
6881       // In C++, we can have a throw-expression, which has 'void' type.
6882       if (!LHSExpr->getType()->isVoidType())
6883         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
6884           return LHS;
6885     }
6886
6887     // In C++, we can have a throw-expression, which has 'void' type.
6888     if (C->getRHS()->getType()->isVoidType())
6889       return nullptr;
6890
6891     return EvalAddr(C->getRHS(), refVars, ParentDecl);
6892   }
6893
6894   case Stmt::BlockExprClass:
6895     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
6896       return E; // local block.
6897     return nullptr;
6898
6899   case Stmt::AddrLabelExprClass:
6900     return E; // address of label.
6901
6902   case Stmt::ExprWithCleanupsClass:
6903     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6904                     ParentDecl);
6905
6906   // For casts, we need to handle conversions from arrays to
6907   // pointer values, and pointer-to-pointer conversions.
6908   case Stmt::ImplicitCastExprClass:
6909   case Stmt::CStyleCastExprClass:
6910   case Stmt::CXXFunctionalCastExprClass:
6911   case Stmt::ObjCBridgedCastExprClass:
6912   case Stmt::CXXStaticCastExprClass:
6913   case Stmt::CXXDynamicCastExprClass:
6914   case Stmt::CXXConstCastExprClass:
6915   case Stmt::CXXReinterpretCastExprClass: {
6916     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
6917     switch (cast<CastExpr>(E)->getCastKind()) {
6918     case CK_LValueToRValue:
6919     case CK_NoOp:
6920     case CK_BaseToDerived:
6921     case CK_DerivedToBase:
6922     case CK_UncheckedDerivedToBase:
6923     case CK_Dynamic:
6924     case CK_CPointerToObjCPointerCast:
6925     case CK_BlockPointerToObjCPointerCast:
6926     case CK_AnyPointerToBlockPointerCast:
6927       return EvalAddr(SubExpr, refVars, ParentDecl);
6928
6929     case CK_ArrayToPointerDecay:
6930       return EvalVal(SubExpr, refVars, ParentDecl);
6931
6932     case CK_BitCast:
6933       if (SubExpr->getType()->isAnyPointerType() ||
6934           SubExpr->getType()->isBlockPointerType() ||
6935           SubExpr->getType()->isObjCQualifiedIdType())
6936         return EvalAddr(SubExpr, refVars, ParentDecl);
6937       else
6938         return nullptr;
6939
6940     default:
6941       return nullptr;
6942     }
6943   }
6944
6945   case Stmt::MaterializeTemporaryExprClass:
6946     if (const Expr *Result =
6947             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6948                      refVars, ParentDecl))
6949       return Result;
6950     return E;
6951
6952   // Everything else: we simply don't reason about them.
6953   default:
6954     return nullptr;
6955   }
6956 }
6957
6958 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
6959 ///   See the comments for EvalAddr for more details.
6960 static const Expr *EvalVal(const Expr *E,
6961                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6962                            const Decl *ParentDecl) {
6963   do {
6964     // We should only be called for evaluating non-pointer expressions, or
6965     // expressions with a pointer type that are not used as references but
6966     // instead
6967     // are l-values (e.g., DeclRefExpr with a pointer type).
6968
6969     // Our "symbolic interpreter" is just a dispatch off the currently
6970     // viewed AST node.  We then recursively traverse the AST by calling
6971     // EvalAddr and EvalVal appropriately.
6972
6973     E = E->IgnoreParens();
6974     switch (E->getStmtClass()) {
6975     case Stmt::ImplicitCastExprClass: {
6976       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6977       if (IE->getValueKind() == VK_LValue) {
6978         E = IE->getSubExpr();
6979         continue;
6980       }
6981       return nullptr;
6982     }
6983
6984     case Stmt::ExprWithCleanupsClass:
6985       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6986                      ParentDecl);
6987
6988     case Stmt::DeclRefExprClass: {
6989       // When we hit a DeclRefExpr we are looking at code that refers to a
6990       // variable's name. If it's not a reference variable we check if it has
6991       // local storage within the function, and if so, return the expression.
6992       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6993
6994       // If we leave the immediate function, the lifetime isn't about to end.
6995       if (DR->refersToEnclosingVariableOrCapture())
6996         return nullptr;
6997
6998       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6999         // Check if it refers to itself, e.g. "int& i = i;".
7000         if (V == ParentDecl)
7001           return DR;
7002
7003         if (V->hasLocalStorage()) {
7004           if (!V->getType()->isReferenceType())
7005             return DR;
7006
7007           // Reference variable, follow through to the expression that
7008           // it points to.
7009           if (V->hasInit()) {
7010             // Add the reference variable to the "trail".
7011             refVars.push_back(DR);
7012             return EvalVal(V->getInit(), refVars, V);
7013           }
7014         }
7015       }
7016
7017       return nullptr;
7018     }
7019
7020     case Stmt::UnaryOperatorClass: {
7021       // The only unary operator that make sense to handle here
7022       // is Deref.  All others don't resolve to a "name."  This includes
7023       // handling all sorts of rvalues passed to a unary operator.
7024       const UnaryOperator *U = cast<UnaryOperator>(E);
7025
7026       if (U->getOpcode() == UO_Deref)
7027         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7028
7029       return nullptr;
7030     }
7031
7032     case Stmt::ArraySubscriptExprClass: {
7033       // Array subscripts are potential references to data on the stack.  We
7034       // retrieve the DeclRefExpr* for the array variable if it indeed
7035       // has local storage.
7036       const auto *ASE = cast<ArraySubscriptExpr>(E);
7037       if (ASE->isTypeDependent())
7038         return nullptr;
7039       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7040     }
7041
7042     case Stmt::OMPArraySectionExprClass: {
7043       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7044                       ParentDecl);
7045     }
7046
7047     case Stmt::ConditionalOperatorClass: {
7048       // For conditional operators we need to see if either the LHS or RHS are
7049       // non-NULL Expr's.  If one is non-NULL, we return it.
7050       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7051
7052       // Handle the GNU extension for missing LHS.
7053       if (const Expr *LHSExpr = C->getLHS()) {
7054         // In C++, we can have a throw-expression, which has 'void' type.
7055         if (!LHSExpr->getType()->isVoidType())
7056           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7057             return LHS;
7058       }
7059
7060       // In C++, we can have a throw-expression, which has 'void' type.
7061       if (C->getRHS()->getType()->isVoidType())
7062         return nullptr;
7063
7064       return EvalVal(C->getRHS(), refVars, ParentDecl);
7065     }
7066
7067     // Accesses to members are potential references to data on the stack.
7068     case Stmt::MemberExprClass: {
7069       const MemberExpr *M = cast<MemberExpr>(E);
7070
7071       // Check for indirect access.  We only want direct field accesses.
7072       if (M->isArrow())
7073         return nullptr;
7074
7075       // Check whether the member type is itself a reference, in which case
7076       // we're not going to refer to the member, but to what the member refers
7077       // to.
7078       if (M->getMemberDecl()->getType()->isReferenceType())
7079         return nullptr;
7080
7081       return EvalVal(M->getBase(), refVars, ParentDecl);
7082     }
7083
7084     case Stmt::MaterializeTemporaryExprClass:
7085       if (const Expr *Result =
7086               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7087                       refVars, ParentDecl))
7088         return Result;
7089       return E;
7090
7091     default:
7092       // Check that we don't return or take the address of a reference to a
7093       // temporary. This is only useful in C++.
7094       if (!E->isTypeDependent() && E->isRValue())
7095         return E;
7096
7097       // Everything else: we simply don't reason about them.
7098       return nullptr;
7099     }
7100   } while (true);
7101 }
7102
7103 void
7104 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7105                          SourceLocation ReturnLoc,
7106                          bool isObjCMethod,
7107                          const AttrVec *Attrs,
7108                          const FunctionDecl *FD) {
7109   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7110
7111   // Check if the return value is null but should not be.
7112   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7113        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7114       CheckNonNullExpr(*this, RetValExp))
7115     Diag(ReturnLoc, diag::warn_null_ret)
7116       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7117
7118   // C++11 [basic.stc.dynamic.allocation]p4:
7119   //   If an allocation function declared with a non-throwing
7120   //   exception-specification fails to allocate storage, it shall return
7121   //   a null pointer. Any other allocation function that fails to allocate
7122   //   storage shall indicate failure only by throwing an exception [...]
7123   if (FD) {
7124     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7125     if (Op == OO_New || Op == OO_Array_New) {
7126       const FunctionProtoType *Proto
7127         = FD->getType()->castAs<FunctionProtoType>();
7128       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7129           CheckNonNullExpr(*this, RetValExp))
7130         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7131           << FD << getLangOpts().CPlusPlus11;
7132     }
7133   }
7134 }
7135
7136 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7137
7138 /// Check for comparisons of floating point operands using != and ==.
7139 /// Issue a warning if these are no self-comparisons, as they are not likely
7140 /// to do what the programmer intended.
7141 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7142   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7143   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7144
7145   // Special case: check for x == x (which is OK).
7146   // Do not emit warnings for such cases.
7147   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7148     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7149       if (DRL->getDecl() == DRR->getDecl())
7150         return;
7151
7152   // Special case: check for comparisons against literals that can be exactly
7153   //  represented by APFloat.  In such cases, do not emit a warning.  This
7154   //  is a heuristic: often comparison against such literals are used to
7155   //  detect if a value in a variable has not changed.  This clearly can
7156   //  lead to false negatives.
7157   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7158     if (FLL->isExact())
7159       return;
7160   } else
7161     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7162       if (FLR->isExact())
7163         return;
7164
7165   // Check for comparisons with builtin types.
7166   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7167     if (CL->getBuiltinCallee())
7168       return;
7169
7170   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7171     if (CR->getBuiltinCallee())
7172       return;
7173
7174   // Emit the diagnostic.
7175   Diag(Loc, diag::warn_floatingpoint_eq)
7176     << LHS->getSourceRange() << RHS->getSourceRange();
7177 }
7178
7179 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7180 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7181
7182 namespace {
7183
7184 /// Structure recording the 'active' range of an integer-valued
7185 /// expression.
7186 struct IntRange {
7187   /// The number of bits active in the int.
7188   unsigned Width;
7189
7190   /// True if the int is known not to have negative values.
7191   bool NonNegative;
7192
7193   IntRange(unsigned Width, bool NonNegative)
7194     : Width(Width), NonNegative(NonNegative)
7195   {}
7196
7197   /// Returns the range of the bool type.
7198   static IntRange forBoolType() {
7199     return IntRange(1, true);
7200   }
7201
7202   /// Returns the range of an opaque value of the given integral type.
7203   static IntRange forValueOfType(ASTContext &C, QualType T) {
7204     return forValueOfCanonicalType(C,
7205                           T->getCanonicalTypeInternal().getTypePtr());
7206   }
7207
7208   /// Returns the range of an opaque value of a canonical integral type.
7209   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7210     assert(T->isCanonicalUnqualified());
7211
7212     if (const VectorType *VT = dyn_cast<VectorType>(T))
7213       T = VT->getElementType().getTypePtr();
7214     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7215       T = CT->getElementType().getTypePtr();
7216     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7217       T = AT->getValueType().getTypePtr();
7218
7219     // For enum types, use the known bit width of the enumerators.
7220     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7221       EnumDecl *Enum = ET->getDecl();
7222       if (!Enum->isCompleteDefinition())
7223         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7224
7225       unsigned NumPositive = Enum->getNumPositiveBits();
7226       unsigned NumNegative = Enum->getNumNegativeBits();
7227
7228       if (NumNegative == 0)
7229         return IntRange(NumPositive, true/*NonNegative*/);
7230       else
7231         return IntRange(std::max(NumPositive + 1, NumNegative),
7232                         false/*NonNegative*/);
7233     }
7234
7235     const BuiltinType *BT = cast<BuiltinType>(T);
7236     assert(BT->isInteger());
7237
7238     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7239   }
7240
7241   /// Returns the "target" range of a canonical integral type, i.e.
7242   /// the range of values expressible in the type.
7243   ///
7244   /// This matches forValueOfCanonicalType except that enums have the
7245   /// full range of their type, not the range of their enumerators.
7246   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7247     assert(T->isCanonicalUnqualified());
7248
7249     if (const VectorType *VT = dyn_cast<VectorType>(T))
7250       T = VT->getElementType().getTypePtr();
7251     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7252       T = CT->getElementType().getTypePtr();
7253     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7254       T = AT->getValueType().getTypePtr();
7255     if (const EnumType *ET = dyn_cast<EnumType>(T))
7256       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7257
7258     const BuiltinType *BT = cast<BuiltinType>(T);
7259     assert(BT->isInteger());
7260
7261     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7262   }
7263
7264   /// Returns the supremum of two ranges: i.e. their conservative merge.
7265   static IntRange join(IntRange L, IntRange R) {
7266     return IntRange(std::max(L.Width, R.Width),
7267                     L.NonNegative && R.NonNegative);
7268   }
7269
7270   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7271   static IntRange meet(IntRange L, IntRange R) {
7272     return IntRange(std::min(L.Width, R.Width),
7273                     L.NonNegative || R.NonNegative);
7274   }
7275 };
7276
7277 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7278   if (value.isSigned() && value.isNegative())
7279     return IntRange(value.getMinSignedBits(), false);
7280
7281   if (value.getBitWidth() > MaxWidth)
7282     value = value.trunc(MaxWidth);
7283
7284   // isNonNegative() just checks the sign bit without considering
7285   // signedness.
7286   return IntRange(value.getActiveBits(), true);
7287 }
7288
7289 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7290                        unsigned MaxWidth) {
7291   if (result.isInt())
7292     return GetValueRange(C, result.getInt(), MaxWidth);
7293
7294   if (result.isVector()) {
7295     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7296     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7297       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7298       R = IntRange::join(R, El);
7299     }
7300     return R;
7301   }
7302
7303   if (result.isComplexInt()) {
7304     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7305     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7306     return IntRange::join(R, I);
7307   }
7308
7309   // This can happen with lossless casts to intptr_t of "based" lvalues.
7310   // Assume it might use arbitrary bits.
7311   // FIXME: The only reason we need to pass the type in here is to get
7312   // the sign right on this one case.  It would be nice if APValue
7313   // preserved this.
7314   assert(result.isLValue() || result.isAddrLabelDiff());
7315   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7316 }
7317
7318 QualType GetExprType(const Expr *E) {
7319   QualType Ty = E->getType();
7320   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7321     Ty = AtomicRHS->getValueType();
7322   return Ty;
7323 }
7324
7325 /// Pseudo-evaluate the given integer expression, estimating the
7326 /// range of values it might take.
7327 ///
7328 /// \param MaxWidth - the width to which the value will be truncated
7329 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7330   E = E->IgnoreParens();
7331
7332   // Try a full evaluation first.
7333   Expr::EvalResult result;
7334   if (E->EvaluateAsRValue(result, C))
7335     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7336
7337   // I think we only want to look through implicit casts here; if the
7338   // user has an explicit widening cast, we should treat the value as
7339   // being of the new, wider type.
7340   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7341     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7342       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7343
7344     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7345
7346     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7347                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7348
7349     // Assume that non-integer casts can span the full range of the type.
7350     if (!isIntegerCast)
7351       return OutputTypeRange;
7352
7353     IntRange SubRange
7354       = GetExprRange(C, CE->getSubExpr(),
7355                      std::min(MaxWidth, OutputTypeRange.Width));
7356
7357     // Bail out if the subexpr's range is as wide as the cast type.
7358     if (SubRange.Width >= OutputTypeRange.Width)
7359       return OutputTypeRange;
7360
7361     // Otherwise, we take the smaller width, and we're non-negative if
7362     // either the output type or the subexpr is.
7363     return IntRange(SubRange.Width,
7364                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7365   }
7366
7367   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7368     // If we can fold the condition, just take that operand.
7369     bool CondResult;
7370     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7371       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7372                                         : CO->getFalseExpr(),
7373                           MaxWidth);
7374
7375     // Otherwise, conservatively merge.
7376     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7377     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7378     return IntRange::join(L, R);
7379   }
7380
7381   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7382     switch (BO->getOpcode()) {
7383
7384     // Boolean-valued operations are single-bit and positive.
7385     case BO_LAnd:
7386     case BO_LOr:
7387     case BO_LT:
7388     case BO_GT:
7389     case BO_LE:
7390     case BO_GE:
7391     case BO_EQ:
7392     case BO_NE:
7393       return IntRange::forBoolType();
7394
7395     // The type of the assignments is the type of the LHS, so the RHS
7396     // is not necessarily the same type.
7397     case BO_MulAssign:
7398     case BO_DivAssign:
7399     case BO_RemAssign:
7400     case BO_AddAssign:
7401     case BO_SubAssign:
7402     case BO_XorAssign:
7403     case BO_OrAssign:
7404       // TODO: bitfields?
7405       return IntRange::forValueOfType(C, GetExprType(E));
7406
7407     // Simple assignments just pass through the RHS, which will have
7408     // been coerced to the LHS type.
7409     case BO_Assign:
7410       // TODO: bitfields?
7411       return GetExprRange(C, BO->getRHS(), MaxWidth);
7412
7413     // Operations with opaque sources are black-listed.
7414     case BO_PtrMemD:
7415     case BO_PtrMemI:
7416       return IntRange::forValueOfType(C, GetExprType(E));
7417
7418     // Bitwise-and uses the *infinum* of the two source ranges.
7419     case BO_And:
7420     case BO_AndAssign:
7421       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7422                             GetExprRange(C, BO->getRHS(), MaxWidth));
7423
7424     // Left shift gets black-listed based on a judgement call.
7425     case BO_Shl:
7426       // ...except that we want to treat '1 << (blah)' as logically
7427       // positive.  It's an important idiom.
7428       if (IntegerLiteral *I
7429             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7430         if (I->getValue() == 1) {
7431           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7432           return IntRange(R.Width, /*NonNegative*/ true);
7433         }
7434       }
7435       // fallthrough
7436
7437     case BO_ShlAssign:
7438       return IntRange::forValueOfType(C, GetExprType(E));
7439
7440     // Right shift by a constant can narrow its left argument.
7441     case BO_Shr:
7442     case BO_ShrAssign: {
7443       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7444
7445       // If the shift amount is a positive constant, drop the width by
7446       // that much.
7447       llvm::APSInt shift;
7448       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7449           shift.isNonNegative()) {
7450         unsigned zext = shift.getZExtValue();
7451         if (zext >= L.Width)
7452           L.Width = (L.NonNegative ? 0 : 1);
7453         else
7454           L.Width -= zext;
7455       }
7456
7457       return L;
7458     }
7459
7460     // Comma acts as its right operand.
7461     case BO_Comma:
7462       return GetExprRange(C, BO->getRHS(), MaxWidth);
7463
7464     // Black-list pointer subtractions.
7465     case BO_Sub:
7466       if (BO->getLHS()->getType()->isPointerType())
7467         return IntRange::forValueOfType(C, GetExprType(E));
7468       break;
7469
7470     // The width of a division result is mostly determined by the size
7471     // of the LHS.
7472     case BO_Div: {
7473       // Don't 'pre-truncate' the operands.
7474       unsigned opWidth = C.getIntWidth(GetExprType(E));
7475       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7476
7477       // If the divisor is constant, use that.
7478       llvm::APSInt divisor;
7479       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7480         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7481         if (log2 >= L.Width)
7482           L.Width = (L.NonNegative ? 0 : 1);
7483         else
7484           L.Width = std::min(L.Width - log2, MaxWidth);
7485         return L;
7486       }
7487
7488       // Otherwise, just use the LHS's width.
7489       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7490       return IntRange(L.Width, L.NonNegative && R.NonNegative);
7491     }
7492
7493     // The result of a remainder can't be larger than the result of
7494     // either side.
7495     case BO_Rem: {
7496       // Don't 'pre-truncate' the operands.
7497       unsigned opWidth = C.getIntWidth(GetExprType(E));
7498       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7499       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7500
7501       IntRange meet = IntRange::meet(L, R);
7502       meet.Width = std::min(meet.Width, MaxWidth);
7503       return meet;
7504     }
7505
7506     // The default behavior is okay for these.
7507     case BO_Mul:
7508     case BO_Add:
7509     case BO_Xor:
7510     case BO_Or:
7511       break;
7512     }
7513
7514     // The default case is to treat the operation as if it were closed
7515     // on the narrowest type that encompasses both operands.
7516     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7517     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7518     return IntRange::join(L, R);
7519   }
7520
7521   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
7522     switch (UO->getOpcode()) {
7523     // Boolean-valued operations are white-listed.
7524     case UO_LNot:
7525       return IntRange::forBoolType();
7526
7527     // Operations with opaque sources are black-listed.
7528     case UO_Deref:
7529     case UO_AddrOf: // should be impossible
7530       return IntRange::forValueOfType(C, GetExprType(E));
7531
7532     default:
7533       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7534     }
7535   }
7536
7537   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7538     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7539
7540   if (const auto *BitField = E->getSourceBitField())
7541     return IntRange(BitField->getBitWidthValue(C),
7542                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
7543
7544   return IntRange::forValueOfType(C, GetExprType(E));
7545 }
7546
7547 IntRange GetExprRange(ASTContext &C, const Expr *E) {
7548   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
7549 }
7550
7551 /// Checks whether the given value, which currently has the given
7552 /// source semantics, has the same value when coerced through the
7553 /// target semantics.
7554 bool IsSameFloatAfterCast(const llvm::APFloat &value,
7555                           const llvm::fltSemantics &Src,
7556                           const llvm::fltSemantics &Tgt) {
7557   llvm::APFloat truncated = value;
7558
7559   bool ignored;
7560   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7561   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7562
7563   return truncated.bitwiseIsEqual(value);
7564 }
7565
7566 /// Checks whether the given value, which currently has the given
7567 /// source semantics, has the same value when coerced through the
7568 /// target semantics.
7569 ///
7570 /// The value might be a vector of floats (or a complex number).
7571 bool IsSameFloatAfterCast(const APValue &value,
7572                           const llvm::fltSemantics &Src,
7573                           const llvm::fltSemantics &Tgt) {
7574   if (value.isFloat())
7575     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7576
7577   if (value.isVector()) {
7578     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7579       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7580         return false;
7581     return true;
7582   }
7583
7584   assert(value.isComplexFloat());
7585   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7586           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7587 }
7588
7589 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
7590
7591 bool IsZero(Sema &S, Expr *E) {
7592   // Suppress cases where we are comparing against an enum constant.
7593   if (const DeclRefExpr *DR =
7594       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7595     if (isa<EnumConstantDecl>(DR->getDecl()))
7596       return false;
7597
7598   // Suppress cases where the '0' value is expanded from a macro.
7599   if (E->getLocStart().isMacroID())
7600     return false;
7601
7602   llvm::APSInt Value;
7603   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7604 }
7605
7606 bool HasEnumType(Expr *E) {
7607   // Strip off implicit integral promotions.
7608   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7609     if (ICE->getCastKind() != CK_IntegralCast &&
7610         ICE->getCastKind() != CK_NoOp)
7611       break;
7612     E = ICE->getSubExpr();
7613   }
7614
7615   return E->getType()->isEnumeralType();
7616 }
7617
7618 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
7619   // Disable warning in template instantiations.
7620   if (!S.ActiveTemplateInstantiations.empty())
7621     return;
7622
7623   BinaryOperatorKind op = E->getOpcode();
7624   if (E->isValueDependent())
7625     return;
7626
7627   if (op == BO_LT && IsZero(S, E->getRHS())) {
7628     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7629       << "< 0" << "false" << HasEnumType(E->getLHS())
7630       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7631   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
7632     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7633       << ">= 0" << "true" << HasEnumType(E->getLHS())
7634       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7635   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
7636     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7637       << "0 >" << "false" << HasEnumType(E->getRHS())
7638       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7639   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
7640     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7641       << "0 <=" << "true" << HasEnumType(E->getRHS())
7642       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7643   }
7644 }
7645
7646 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7647                                   Expr *Other, const llvm::APSInt &Value,
7648                                   bool RhsConstant) {
7649   // Disable warning in template instantiations.
7650   if (!S.ActiveTemplateInstantiations.empty())
7651     return;
7652
7653   // TODO: Investigate using GetExprRange() to get tighter bounds
7654   // on the bit ranges.
7655   QualType OtherT = Other->getType();
7656   if (const auto *AT = OtherT->getAs<AtomicType>())
7657     OtherT = AT->getValueType();
7658   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7659   unsigned OtherWidth = OtherRange.Width;
7660
7661   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7662
7663   // 0 values are handled later by CheckTrivialUnsignedComparison().
7664   if ((Value == 0) && (!OtherIsBooleanType))
7665     return;
7666
7667   BinaryOperatorKind op = E->getOpcode();
7668   bool IsTrue = true;
7669
7670   // Used for diagnostic printout.
7671   enum {
7672     LiteralConstant = 0,
7673     CXXBoolLiteralTrue,
7674     CXXBoolLiteralFalse
7675   } LiteralOrBoolConstant = LiteralConstant;
7676
7677   if (!OtherIsBooleanType) {
7678     QualType ConstantT = Constant->getType();
7679     QualType CommonT = E->getLHS()->getType();
7680
7681     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7682       return;
7683     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7684            "comparison with non-integer type");
7685
7686     bool ConstantSigned = ConstantT->isSignedIntegerType();
7687     bool CommonSigned = CommonT->isSignedIntegerType();
7688
7689     bool EqualityOnly = false;
7690
7691     if (CommonSigned) {
7692       // The common type is signed, therefore no signed to unsigned conversion.
7693       if (!OtherRange.NonNegative) {
7694         // Check that the constant is representable in type OtherT.
7695         if (ConstantSigned) {
7696           if (OtherWidth >= Value.getMinSignedBits())
7697             return;
7698         } else { // !ConstantSigned
7699           if (OtherWidth >= Value.getActiveBits() + 1)
7700             return;
7701         }
7702       } else { // !OtherSigned
7703                // Check that the constant is representable in type OtherT.
7704         // Negative values are out of range.
7705         if (ConstantSigned) {
7706           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7707             return;
7708         } else { // !ConstantSigned
7709           if (OtherWidth >= Value.getActiveBits())
7710             return;
7711         }
7712       }
7713     } else { // !CommonSigned
7714       if (OtherRange.NonNegative) {
7715         if (OtherWidth >= Value.getActiveBits())
7716           return;
7717       } else { // OtherSigned
7718         assert(!ConstantSigned &&
7719                "Two signed types converted to unsigned types.");
7720         // Check to see if the constant is representable in OtherT.
7721         if (OtherWidth > Value.getActiveBits())
7722           return;
7723         // Check to see if the constant is equivalent to a negative value
7724         // cast to CommonT.
7725         if (S.Context.getIntWidth(ConstantT) ==
7726                 S.Context.getIntWidth(CommonT) &&
7727             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7728           return;
7729         // The constant value rests between values that OtherT can represent
7730         // after conversion.  Relational comparison still works, but equality
7731         // comparisons will be tautological.
7732         EqualityOnly = true;
7733       }
7734     }
7735
7736     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7737
7738     if (op == BO_EQ || op == BO_NE) {
7739       IsTrue = op == BO_NE;
7740     } else if (EqualityOnly) {
7741       return;
7742     } else if (RhsConstant) {
7743       if (op == BO_GT || op == BO_GE)
7744         IsTrue = !PositiveConstant;
7745       else // op == BO_LT || op == BO_LE
7746         IsTrue = PositiveConstant;
7747     } else {
7748       if (op == BO_LT || op == BO_LE)
7749         IsTrue = !PositiveConstant;
7750       else // op == BO_GT || op == BO_GE
7751         IsTrue = PositiveConstant;
7752     }
7753   } else {
7754     // Other isKnownToHaveBooleanValue
7755     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7756     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7757     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7758
7759     static const struct LinkedConditions {
7760       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7761       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7762       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7763       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7764       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7765       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7766
7767     } TruthTable = {
7768         // Constant on LHS.              | Constant on RHS.              |
7769         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
7770         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7771         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7772         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7773         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7774         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7775         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7776       };
7777
7778     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7779
7780     enum ConstantValue ConstVal = Zero;
7781     if (Value.isUnsigned() || Value.isNonNegative()) {
7782       if (Value == 0) {
7783         LiteralOrBoolConstant =
7784             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7785         ConstVal = Zero;
7786       } else if (Value == 1) {
7787         LiteralOrBoolConstant =
7788             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7789         ConstVal = One;
7790       } else {
7791         LiteralOrBoolConstant = LiteralConstant;
7792         ConstVal = GT_One;
7793       }
7794     } else {
7795       ConstVal = LT_Zero;
7796     }
7797
7798     CompareBoolWithConstantResult CmpRes;
7799
7800     switch (op) {
7801     case BO_LT:
7802       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7803       break;
7804     case BO_GT:
7805       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7806       break;
7807     case BO_LE:
7808       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7809       break;
7810     case BO_GE:
7811       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7812       break;
7813     case BO_EQ:
7814       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7815       break;
7816     case BO_NE:
7817       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7818       break;
7819     default:
7820       CmpRes = Unkwn;
7821       break;
7822     }
7823
7824     if (CmpRes == AFals) {
7825       IsTrue = false;
7826     } else if (CmpRes == ATrue) {
7827       IsTrue = true;
7828     } else {
7829       return;
7830     }
7831   }
7832
7833   // If this is a comparison to an enum constant, include that
7834   // constant in the diagnostic.
7835   const EnumConstantDecl *ED = nullptr;
7836   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7837     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7838
7839   SmallString<64> PrettySourceValue;
7840   llvm::raw_svector_ostream OS(PrettySourceValue);
7841   if (ED)
7842     OS << '\'' << *ED << "' (" << Value << ")";
7843   else
7844     OS << Value;
7845
7846   S.DiagRuntimeBehavior(
7847     E->getOperatorLoc(), E,
7848     S.PDiag(diag::warn_out_of_range_compare)
7849         << OS.str() << LiteralOrBoolConstant
7850         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7851         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
7852 }
7853
7854 /// Analyze the operands of the given comparison.  Implements the
7855 /// fallback case from AnalyzeComparison.
7856 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
7857   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7858   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7859 }
7860
7861 /// \brief Implements -Wsign-compare.
7862 ///
7863 /// \param E the binary operator to check for warnings
7864 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
7865   // The type the comparison is being performed in.
7866   QualType T = E->getLHS()->getType();
7867
7868   // Only analyze comparison operators where both sides have been converted to
7869   // the same type.
7870   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7871     return AnalyzeImpConvsInComparison(S, E);
7872
7873   // Don't analyze value-dependent comparisons directly.
7874   if (E->isValueDependent())
7875     return AnalyzeImpConvsInComparison(S, E);
7876
7877   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7878   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
7879   
7880   bool IsComparisonConstant = false;
7881   
7882   // Check whether an integer constant comparison results in a value
7883   // of 'true' or 'false'.
7884   if (T->isIntegralType(S.Context)) {
7885     llvm::APSInt RHSValue;
7886     bool IsRHSIntegralLiteral = 
7887       RHS->isIntegerConstantExpr(RHSValue, S.Context);
7888     llvm::APSInt LHSValue;
7889     bool IsLHSIntegralLiteral = 
7890       LHS->isIntegerConstantExpr(LHSValue, S.Context);
7891     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7892         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7893     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7894       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7895     else
7896       IsComparisonConstant = 
7897         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
7898   } else if (!T->hasUnsignedIntegerRepresentation())
7899       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
7900   
7901   // We don't do anything special if this isn't an unsigned integral
7902   // comparison:  we're only interested in integral comparisons, and
7903   // signed comparisons only happen in cases we don't care to warn about.
7904   //
7905   // We also don't care about value-dependent expressions or expressions
7906   // whose result is a constant.
7907   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
7908     return AnalyzeImpConvsInComparison(S, E);
7909   
7910   // Check to see if one of the (unmodified) operands is of different
7911   // signedness.
7912   Expr *signedOperand, *unsignedOperand;
7913   if (LHS->getType()->hasSignedIntegerRepresentation()) {
7914     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
7915            "unsigned comparison between two signed integer expressions?");
7916     signedOperand = LHS;
7917     unsignedOperand = RHS;
7918   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7919     signedOperand = RHS;
7920     unsignedOperand = LHS;
7921   } else {
7922     CheckTrivialUnsignedComparison(S, E);
7923     return AnalyzeImpConvsInComparison(S, E);
7924   }
7925
7926   // Otherwise, calculate the effective range of the signed operand.
7927   IntRange signedRange = GetExprRange(S.Context, signedOperand);
7928
7929   // Go ahead and analyze implicit conversions in the operands.  Note
7930   // that we skip the implicit conversions on both sides.
7931   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7932   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
7933
7934   // If the signed range is non-negative, -Wsign-compare won't fire,
7935   // but we should still check for comparisons which are always true
7936   // or false.
7937   if (signedRange.NonNegative)
7938     return CheckTrivialUnsignedComparison(S, E);
7939
7940   // For (in)equality comparisons, if the unsigned operand is a
7941   // constant which cannot collide with a overflowed signed operand,
7942   // then reinterpreting the signed operand as unsigned will not
7943   // change the result of the comparison.
7944   if (E->isEqualityOp()) {
7945     unsigned comparisonWidth = S.Context.getIntWidth(T);
7946     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
7947
7948     // We should never be unable to prove that the unsigned operand is
7949     // non-negative.
7950     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7951
7952     if (unsignedRange.Width < comparisonWidth)
7953       return;
7954   }
7955
7956   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7957     S.PDiag(diag::warn_mixed_sign_comparison)
7958       << LHS->getType() << RHS->getType()
7959       << LHS->getSourceRange() << RHS->getSourceRange());
7960 }
7961
7962 /// Analyzes an attempt to assign the given value to a bitfield.
7963 ///
7964 /// Returns true if there was something fishy about the attempt.
7965 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7966                                SourceLocation InitLoc) {
7967   assert(Bitfield->isBitField());
7968   if (Bitfield->isInvalidDecl())
7969     return false;
7970
7971   // White-list bool bitfields.
7972   if (Bitfield->getType()->isBooleanType())
7973     return false;
7974
7975   // Ignore value- or type-dependent expressions.
7976   if (Bitfield->getBitWidth()->isValueDependent() ||
7977       Bitfield->getBitWidth()->isTypeDependent() ||
7978       Init->isValueDependent() ||
7979       Init->isTypeDependent())
7980     return false;
7981
7982   Expr *OriginalInit = Init->IgnoreParenImpCasts();
7983
7984   llvm::APSInt Value;
7985   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
7986     return false;
7987
7988   unsigned OriginalWidth = Value.getBitWidth();
7989   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
7990
7991   if (Value.isSigned() && Value.isNegative())
7992     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7993       if (UO->getOpcode() == UO_Minus)
7994         if (isa<IntegerLiteral>(UO->getSubExpr()))
7995           OriginalWidth = Value.getMinSignedBits();
7996
7997   if (OriginalWidth <= FieldWidth)
7998     return false;
7999
8000   // Compute the value which the bitfield will contain.
8001   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8002   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
8003
8004   // Check whether the stored value is equal to the original value.
8005   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8006   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8007     return false;
8008
8009   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8010   // therefore don't strictly fit into a signed bitfield of width 1.
8011   if (FieldWidth == 1 && Value == 1)
8012     return false;
8013
8014   std::string PrettyValue = Value.toString(10);
8015   std::string PrettyTrunc = TruncatedValue.toString(10);
8016
8017   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8018     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8019     << Init->getSourceRange();
8020
8021   return true;
8022 }
8023
8024 /// Analyze the given simple or compound assignment for warning-worthy
8025 /// operations.
8026 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8027   // Just recurse on the LHS.
8028   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8029
8030   // We want to recurse on the RHS as normal unless we're assigning to
8031   // a bitfield.
8032   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8033     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8034                                   E->getOperatorLoc())) {
8035       // Recurse, ignoring any implicit conversions on the RHS.
8036       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8037                                         E->getOperatorLoc());
8038     }
8039   }
8040
8041   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8042 }
8043
8044 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8045 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 
8046                      SourceLocation CContext, unsigned diag,
8047                      bool pruneControlFlow = false) {
8048   if (pruneControlFlow) {
8049     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8050                           S.PDiag(diag)
8051                             << SourceType << T << E->getSourceRange()
8052                             << SourceRange(CContext));
8053     return;
8054   }
8055   S.Diag(E->getExprLoc(), diag)
8056     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8057 }
8058
8059 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8060 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8061                      unsigned diag, bool pruneControlFlow = false) {
8062   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8063 }
8064
8065
8066 /// Diagnose an implicit cast from a floating point value to an integer value.
8067 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8068
8069                              SourceLocation CContext) {
8070   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8071   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8072
8073   Expr *InnerE = E->IgnoreParenImpCasts();
8074   // We also want to warn on, e.g., "int i = -1.234"
8075   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8076     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8077       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8078
8079   const bool IsLiteral =
8080       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8081
8082   llvm::APFloat Value(0.0);
8083   bool IsConstant =
8084     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8085   if (!IsConstant) {
8086     return DiagnoseImpCast(S, E, T, CContext,
8087                            diag::warn_impcast_float_integer, PruneWarnings);
8088   }
8089
8090   bool isExact = false;
8091
8092   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8093                             T->hasUnsignedIntegerRepresentation());
8094   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8095                              &isExact) == llvm::APFloat::opOK &&
8096       isExact) {
8097     if (IsLiteral) return;
8098     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8099                            PruneWarnings);
8100   }
8101
8102   unsigned DiagID = 0;
8103   if (IsLiteral) {
8104     // Warn on floating point literal to integer.
8105     DiagID = diag::warn_impcast_literal_float_to_integer;
8106   } else if (IntegerValue == 0) {
8107     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8108       return DiagnoseImpCast(S, E, T, CContext,
8109                              diag::warn_impcast_float_integer, PruneWarnings);
8110     }
8111     // Warn on non-zero to zero conversion.
8112     DiagID = diag::warn_impcast_float_to_integer_zero;
8113   } else {
8114     if (IntegerValue.isUnsigned()) {
8115       if (!IntegerValue.isMaxValue()) {
8116         return DiagnoseImpCast(S, E, T, CContext,
8117                                diag::warn_impcast_float_integer, PruneWarnings);
8118       }
8119     } else {  // IntegerValue.isSigned()
8120       if (!IntegerValue.isMaxSignedValue() &&
8121           !IntegerValue.isMinSignedValue()) {
8122         return DiagnoseImpCast(S, E, T, CContext,
8123                                diag::warn_impcast_float_integer, PruneWarnings);
8124       }
8125     }
8126     // Warn on evaluatable floating point expression to integer conversion.
8127     DiagID = diag::warn_impcast_float_to_integer;
8128   }
8129
8130   // FIXME: Force the precision of the source value down so we don't print
8131   // digits which are usually useless (we don't really care here if we
8132   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8133   // would automatically print the shortest representation, but it's a bit
8134   // tricky to implement.
8135   SmallString<16> PrettySourceValue;
8136   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8137   precision = (precision * 59 + 195) / 196;
8138   Value.toString(PrettySourceValue, precision);
8139
8140   SmallString<16> PrettyTargetValue;
8141   if (IsBool)
8142     PrettyTargetValue = Value.isZero() ? "false" : "true";
8143   else
8144     IntegerValue.toString(PrettyTargetValue);
8145
8146   if (PruneWarnings) {
8147     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8148                           S.PDiag(DiagID)
8149                               << E->getType() << T.getUnqualifiedType()
8150                               << PrettySourceValue << PrettyTargetValue
8151                               << E->getSourceRange() << SourceRange(CContext));
8152   } else {
8153     S.Diag(E->getExprLoc(), DiagID)
8154         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8155         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8156   }
8157 }
8158
8159 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8160   if (!Range.Width) return "0";
8161
8162   llvm::APSInt ValueInRange = Value;
8163   ValueInRange.setIsSigned(!Range.NonNegative);
8164   ValueInRange = ValueInRange.trunc(Range.Width);
8165   return ValueInRange.toString(10);
8166 }
8167
8168 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8169   if (!isa<ImplicitCastExpr>(Ex))
8170     return false;
8171
8172   Expr *InnerE = Ex->IgnoreParenImpCasts();
8173   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8174   const Type *Source =
8175     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8176   if (Target->isDependentType())
8177     return false;
8178
8179   const BuiltinType *FloatCandidateBT =
8180     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8181   const Type *BoolCandidateType = ToBool ? Target : Source;
8182
8183   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8184           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8185 }
8186
8187 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8188                                       SourceLocation CC) {
8189   unsigned NumArgs = TheCall->getNumArgs();
8190   for (unsigned i = 0; i < NumArgs; ++i) {
8191     Expr *CurrA = TheCall->getArg(i);
8192     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8193       continue;
8194
8195     bool IsSwapped = ((i > 0) &&
8196         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8197     IsSwapped |= ((i < (NumArgs - 1)) &&
8198         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8199     if (IsSwapped) {
8200       // Warn on this floating-point to bool conversion.
8201       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8202                       CurrA->getType(), CC,
8203                       diag::warn_impcast_floating_point_to_bool);
8204     }
8205   }
8206 }
8207
8208 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8209   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8210                         E->getExprLoc()))
8211     return;
8212
8213   // Don't warn on functions which have return type nullptr_t.
8214   if (isa<CallExpr>(E))
8215     return;
8216
8217   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8218   const Expr::NullPointerConstantKind NullKind =
8219       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8220   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8221     return;
8222
8223   // Return if target type is a safe conversion.
8224   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8225       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8226     return;
8227
8228   SourceLocation Loc = E->getSourceRange().getBegin();
8229
8230   // Venture through the macro stacks to get to the source of macro arguments.
8231   // The new location is a better location than the complete location that was
8232   // passed in.
8233   while (S.SourceMgr.isMacroArgExpansion(Loc))
8234     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8235
8236   while (S.SourceMgr.isMacroArgExpansion(CC))
8237     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8238
8239   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8240   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8241     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8242         Loc, S.SourceMgr, S.getLangOpts());
8243     if (MacroName == "NULL")
8244       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8245   }
8246
8247   // Only warn if the null and context location are in the same macro expansion.
8248   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8249     return;
8250
8251   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8252       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8253       << FixItHint::CreateReplacement(Loc,
8254                                       S.getFixItZeroLiteralForType(T, Loc));
8255 }
8256
8257 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8258                            ObjCArrayLiteral *ArrayLiteral);
8259 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8260                                 ObjCDictionaryLiteral *DictionaryLiteral);
8261
8262 /// Check a single element within a collection literal against the
8263 /// target element type.
8264 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8265                                        Expr *Element, unsigned ElementKind) {
8266   // Skip a bitcast to 'id' or qualified 'id'.
8267   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8268     if (ICE->getCastKind() == CK_BitCast &&
8269         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8270       Element = ICE->getSubExpr();
8271   }
8272
8273   QualType ElementType = Element->getType();
8274   ExprResult ElementResult(Element);
8275   if (ElementType->getAs<ObjCObjectPointerType>() &&
8276       S.CheckSingleAssignmentConstraints(TargetElementType,
8277                                          ElementResult,
8278                                          false, false)
8279         != Sema::Compatible) {
8280     S.Diag(Element->getLocStart(),
8281            diag::warn_objc_collection_literal_element)
8282       << ElementType << ElementKind << TargetElementType
8283       << Element->getSourceRange();
8284   }
8285
8286   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8287     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8288   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8289     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8290 }
8291
8292 /// Check an Objective-C array literal being converted to the given
8293 /// target type.
8294 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8295                            ObjCArrayLiteral *ArrayLiteral) {
8296   if (!S.NSArrayDecl)
8297     return;
8298
8299   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8300   if (!TargetObjCPtr)
8301     return;
8302
8303   if (TargetObjCPtr->isUnspecialized() ||
8304       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8305         != S.NSArrayDecl->getCanonicalDecl())
8306     return;
8307
8308   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8309   if (TypeArgs.size() != 1)
8310     return;
8311
8312   QualType TargetElementType = TypeArgs[0];
8313   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8314     checkObjCCollectionLiteralElement(S, TargetElementType,
8315                                       ArrayLiteral->getElement(I),
8316                                       0);
8317   }
8318 }
8319
8320 /// Check an Objective-C dictionary literal being converted to the given
8321 /// target type.
8322 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8323                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8324   if (!S.NSDictionaryDecl)
8325     return;
8326
8327   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8328   if (!TargetObjCPtr)
8329     return;
8330
8331   if (TargetObjCPtr->isUnspecialized() ||
8332       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8333         != S.NSDictionaryDecl->getCanonicalDecl())
8334     return;
8335
8336   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8337   if (TypeArgs.size() != 2)
8338     return;
8339
8340   QualType TargetKeyType = TypeArgs[0];
8341   QualType TargetObjectType = TypeArgs[1];
8342   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8343     auto Element = DictionaryLiteral->getKeyValueElement(I);
8344     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8345     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8346   }
8347 }
8348
8349 // Helper function to filter out cases for constant width constant conversion.
8350 // Don't warn on char array initialization or for non-decimal values.
8351 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8352                                    SourceLocation CC) {
8353   // If initializing from a constant, and the constant starts with '0',
8354   // then it is a binary, octal, or hexadecimal.  Allow these constants
8355   // to fill all the bits, even if there is a sign change.
8356   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8357     const char FirstLiteralCharacter =
8358         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8359     if (FirstLiteralCharacter == '0')
8360       return false;
8361   }
8362
8363   // If the CC location points to a '{', and the type is char, then assume
8364   // assume it is an array initialization.
8365   if (CC.isValid() && T->isCharType()) {
8366     const char FirstContextCharacter =
8367         S.getSourceManager().getCharacterData(CC)[0];
8368     if (FirstContextCharacter == '{')
8369       return false;
8370   }
8371
8372   return true;
8373 }
8374
8375 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8376                              SourceLocation CC, bool *ICContext = nullptr) {
8377   if (E->isTypeDependent() || E->isValueDependent()) return;
8378
8379   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8380   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8381   if (Source == Target) return;
8382   if (Target->isDependentType()) return;
8383
8384   // If the conversion context location is invalid don't complain. We also
8385   // don't want to emit a warning if the issue occurs from the expansion of
8386   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8387   // delay this check as long as possible. Once we detect we are in that
8388   // scenario, we just return.
8389   if (CC.isInvalid())
8390     return;
8391
8392   // Diagnose implicit casts to bool.
8393   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8394     if (isa<StringLiteral>(E))
8395       // Warn on string literal to bool.  Checks for string literals in logical
8396       // and expressions, for instance, assert(0 && "error here"), are
8397       // prevented by a check in AnalyzeImplicitConversions().
8398       return DiagnoseImpCast(S, E, T, CC,
8399                              diag::warn_impcast_string_literal_to_bool);
8400     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8401         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8402       // This covers the literal expressions that evaluate to Objective-C
8403       // objects.
8404       return DiagnoseImpCast(S, E, T, CC,
8405                              diag::warn_impcast_objective_c_literal_to_bool);
8406     }
8407     if (Source->isPointerType() || Source->canDecayToPointerType()) {
8408       // Warn on pointer to bool conversion that is always true.
8409       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8410                                      SourceRange(CC));
8411     }
8412   }
8413
8414   // Check implicit casts from Objective-C collection literals to specialized
8415   // collection types, e.g., NSArray<NSString *> *.
8416   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8417     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8418   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8419     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8420
8421   // Strip vector types.
8422   if (isa<VectorType>(Source)) {
8423     if (!isa<VectorType>(Target)) {
8424       if (S.SourceMgr.isInSystemMacro(CC))
8425         return;
8426       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8427     }
8428     
8429     // If the vector cast is cast between two vectors of the same size, it is
8430     // a bitcast, not a conversion.
8431     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8432       return;
8433
8434     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8435     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8436   }
8437   if (auto VecTy = dyn_cast<VectorType>(Target))
8438     Target = VecTy->getElementType().getTypePtr();
8439
8440   // Strip complex types.
8441   if (isa<ComplexType>(Source)) {
8442     if (!isa<ComplexType>(Target)) {
8443       if (S.SourceMgr.isInSystemMacro(CC))
8444         return;
8445
8446       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8447     }
8448
8449     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8450     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8451   }
8452
8453   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8454   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8455
8456   // If the source is floating point...
8457   if (SourceBT && SourceBT->isFloatingPoint()) {
8458     // ...and the target is floating point...
8459     if (TargetBT && TargetBT->isFloatingPoint()) {
8460       // ...then warn if we're dropping FP rank.
8461
8462       // Builtin FP kinds are ordered by increasing FP rank.
8463       if (SourceBT->getKind() > TargetBT->getKind()) {
8464         // Don't warn about float constants that are precisely
8465         // representable in the target type.
8466         Expr::EvalResult result;
8467         if (E->EvaluateAsRValue(result, S.Context)) {
8468           // Value might be a float, a float vector, or a float complex.
8469           if (IsSameFloatAfterCast(result.Val,
8470                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8471                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
8472             return;
8473         }
8474
8475         if (S.SourceMgr.isInSystemMacro(CC))
8476           return;
8477
8478         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8479       }
8480       // ... or possibly if we're increasing rank, too
8481       else if (TargetBT->getKind() > SourceBT->getKind()) {
8482         if (S.SourceMgr.isInSystemMacro(CC))
8483           return;
8484
8485         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8486       }
8487       return;
8488     }
8489
8490     // If the target is integral, always warn.
8491     if (TargetBT && TargetBT->isInteger()) {
8492       if (S.SourceMgr.isInSystemMacro(CC))
8493         return;
8494
8495       DiagnoseFloatingImpCast(S, E, T, CC);
8496     }
8497
8498     // Detect the case where a call result is converted from floating-point to
8499     // to bool, and the final argument to the call is converted from bool, to
8500     // discover this typo:
8501     //
8502     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
8503     //
8504     // FIXME: This is an incredibly special case; is there some more general
8505     // way to detect this class of misplaced-parentheses bug?
8506     if (Target->isBooleanType() && isa<CallExpr>(E)) {
8507       // Check last argument of function call to see if it is an
8508       // implicit cast from a type matching the type the result
8509       // is being cast to.
8510       CallExpr *CEx = cast<CallExpr>(E);
8511       if (unsigned NumArgs = CEx->getNumArgs()) {
8512         Expr *LastA = CEx->getArg(NumArgs - 1);
8513         Expr *InnerE = LastA->IgnoreParenImpCasts();
8514         if (isa<ImplicitCastExpr>(LastA) &&
8515             InnerE->getType()->isBooleanType()) {
8516           // Warn on this floating-point to bool conversion
8517           DiagnoseImpCast(S, E, T, CC,
8518                           diag::warn_impcast_floating_point_to_bool);
8519         }
8520       }
8521     }
8522     return;
8523   }
8524
8525   DiagnoseNullConversion(S, E, T, CC);
8526
8527   if (!Source->isIntegerType() || !Target->isIntegerType())
8528     return;
8529
8530   // TODO: remove this early return once the false positives for constant->bool
8531   // in templates, macros, etc, are reduced or removed.
8532   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8533     return;
8534
8535   IntRange SourceRange = GetExprRange(S.Context, E);
8536   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
8537
8538   if (SourceRange.Width > TargetRange.Width) {
8539     // If the source is a constant, use a default-on diagnostic.
8540     // TODO: this should happen for bitfield stores, too.
8541     llvm::APSInt Value(32);
8542     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
8543       if (S.SourceMgr.isInSystemMacro(CC))
8544         return;
8545
8546       std::string PrettySourceValue = Value.toString(10);
8547       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8548
8549       S.DiagRuntimeBehavior(E->getExprLoc(), E,
8550         S.PDiag(diag::warn_impcast_integer_precision_constant)
8551             << PrettySourceValue << PrettyTargetValue
8552             << E->getType() << T << E->getSourceRange()
8553             << clang::SourceRange(CC));
8554       return;
8555     }
8556
8557     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8558     if (S.SourceMgr.isInSystemMacro(CC))
8559       return;
8560
8561     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
8562       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8563                              /* pruneControlFlow */ true);
8564     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8565   }
8566
8567   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8568       SourceRange.NonNegative && Source->isSignedIntegerType()) {
8569     // Warn when doing a signed to signed conversion, warn if the positive
8570     // source value is exactly the width of the target type, which will
8571     // cause a negative value to be stored.
8572
8573     llvm::APSInt Value;
8574     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8575         !S.SourceMgr.isInSystemMacro(CC)) {
8576       if (isSameWidthConstantConversion(S, E, T, CC)) {
8577         std::string PrettySourceValue = Value.toString(10);
8578         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8579
8580         S.DiagRuntimeBehavior(
8581             E->getExprLoc(), E,
8582             S.PDiag(diag::warn_impcast_integer_precision_constant)
8583                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8584                 << E->getSourceRange() << clang::SourceRange(CC));
8585         return;
8586       }
8587     }
8588
8589     // Fall through for non-constants to give a sign conversion warning.
8590   }
8591
8592   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8593       (!TargetRange.NonNegative && SourceRange.NonNegative &&
8594        SourceRange.Width == TargetRange.Width)) {
8595     if (S.SourceMgr.isInSystemMacro(CC))
8596       return;
8597
8598     unsigned DiagID = diag::warn_impcast_integer_sign;
8599
8600     // Traditionally, gcc has warned about this under -Wsign-compare.
8601     // We also want to warn about it in -Wconversion.
8602     // So if -Wconversion is off, use a completely identical diagnostic
8603     // in the sign-compare group.
8604     // The conditional-checking code will 
8605     if (ICContext) {
8606       DiagID = diag::warn_impcast_integer_sign_conditional;
8607       *ICContext = true;
8608     }
8609
8610     return DiagnoseImpCast(S, E, T, CC, DiagID);
8611   }
8612
8613   // Diagnose conversions between different enumeration types.
8614   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8615   // type, to give us better diagnostics.
8616   QualType SourceType = E->getType();
8617   if (!S.getLangOpts().CPlusPlus) {
8618     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8619       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8620         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8621         SourceType = S.Context.getTypeDeclType(Enum);
8622         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8623       }
8624   }
8625   
8626   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8627     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
8628       if (SourceEnum->getDecl()->hasNameForLinkage() &&
8629           TargetEnum->getDecl()->hasNameForLinkage() &&
8630           SourceEnum != TargetEnum) {
8631         if (S.SourceMgr.isInSystemMacro(CC))
8632           return;
8633
8634         return DiagnoseImpCast(S, E, SourceType, T, CC, 
8635                                diag::warn_impcast_different_enum_types);
8636       }
8637 }
8638
8639 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8640                               SourceLocation CC, QualType T);
8641
8642 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
8643                              SourceLocation CC, bool &ICContext) {
8644   E = E->IgnoreParenImpCasts();
8645
8646   if (isa<ConditionalOperator>(E))
8647     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
8648
8649   AnalyzeImplicitConversions(S, E, CC);
8650   if (E->getType() != T)
8651     return CheckImplicitConversion(S, E, T, CC, &ICContext);
8652 }
8653
8654 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8655                               SourceLocation CC, QualType T) {
8656   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
8657
8658   bool Suspicious = false;
8659   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8660   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
8661
8662   // If -Wconversion would have warned about either of the candidates
8663   // for a signedness conversion to the context type...
8664   if (!Suspicious) return;
8665
8666   // ...but it's currently ignored...
8667   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
8668     return;
8669
8670   // ...then check whether it would have warned about either of the
8671   // candidates for a signedness conversion to the condition type.
8672   if (E->getType() == T) return;
8673  
8674   Suspicious = false;
8675   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8676                           E->getType(), CC, &Suspicious);
8677   if (!Suspicious)
8678     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
8679                             E->getType(), CC, &Suspicious);
8680 }
8681
8682 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8683 /// Input argument E is a logical expression.
8684 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
8685   if (S.getLangOpts().Bool)
8686     return;
8687   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8688 }
8689
8690 /// AnalyzeImplicitConversions - Find and report any interesting
8691 /// implicit conversions in the given expression.  There are a couple
8692 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
8693 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
8694   QualType T = OrigE->getType();
8695   Expr *E = OrigE->IgnoreParenImpCasts();
8696
8697   if (E->isTypeDependent() || E->isValueDependent())
8698     return;
8699   
8700   // For conditional operators, we analyze the arguments as if they
8701   // were being fed directly into the output.
8702   if (isa<ConditionalOperator>(E)) {
8703     ConditionalOperator *CO = cast<ConditionalOperator>(E);
8704     CheckConditionalOperator(S, CO, CC, T);
8705     return;
8706   }
8707
8708   // Check implicit argument conversions for function calls.
8709   if (CallExpr *Call = dyn_cast<CallExpr>(E))
8710     CheckImplicitArgumentConversions(S, Call, CC);
8711
8712   // Go ahead and check any implicit conversions we might have skipped.
8713   // The non-canonical typecheck is just an optimization;
8714   // CheckImplicitConversion will filter out dead implicit conversions.
8715   if (E->getType() != T)
8716     CheckImplicitConversion(S, E, T, CC);
8717
8718   // Now continue drilling into this expression.
8719
8720   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8721     // The bound subexpressions in a PseudoObjectExpr are not reachable
8722     // as transitive children.
8723     // FIXME: Use a more uniform representation for this.
8724     for (auto *SE : POE->semantics())
8725       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8726         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8727   }
8728
8729   // Skip past explicit casts.
8730   if (isa<ExplicitCastExpr>(E)) {
8731     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
8732     return AnalyzeImplicitConversions(S, E, CC);
8733   }
8734
8735   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8736     // Do a somewhat different check with comparison operators.
8737     if (BO->isComparisonOp())
8738       return AnalyzeComparison(S, BO);
8739
8740     // And with simple assignments.
8741     if (BO->getOpcode() == BO_Assign)
8742       return AnalyzeAssignment(S, BO);
8743   }
8744
8745   // These break the otherwise-useful invariant below.  Fortunately,
8746   // we don't really need to recurse into them, because any internal
8747   // expressions should have been analyzed already when they were
8748   // built into statements.
8749   if (isa<StmtExpr>(E)) return;
8750
8751   // Don't descend into unevaluated contexts.
8752   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
8753
8754   // Now just recurse over the expression's children.
8755   CC = E->getExprLoc();
8756   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
8757   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
8758   for (Stmt *SubStmt : E->children()) {
8759     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8760     if (!ChildExpr)
8761       continue;
8762
8763     if (IsLogicalAndOperator &&
8764         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
8765       // Ignore checking string literals that are in logical and operators.
8766       // This is a common pattern for asserts.
8767       continue;
8768     AnalyzeImplicitConversions(S, ChildExpr, CC);
8769   }
8770
8771   if (BO && BO->isLogicalOp()) {
8772     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8773     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8774       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8775
8776     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8777     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8778       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8779   }
8780
8781   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8782     if (U->getOpcode() == UO_LNot)
8783       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8784 }
8785
8786 } // end anonymous namespace
8787
8788 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8789                                             unsigned Start, unsigned End) {
8790   bool IllegalParams = false;
8791   for (unsigned I = Start; I <= End; ++I) {
8792     QualType Ty = TheCall->getArg(I)->getType();
8793     // Taking into account implicit conversions,
8794     // allow any integer within 32 bits range
8795     if (!Ty->isIntegerType() ||
8796         S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8797       S.Diag(TheCall->getArg(I)->getLocStart(),
8798              diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8799       IllegalParams = true;
8800     }
8801     // Potentially emit standard warnings for implicit conversions if enabled
8802     // using -Wconversion.
8803     CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8804                             TheCall->getArg(I)->getLocStart());
8805   }
8806   return IllegalParams;
8807 }
8808
8809 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8810 // Returns true when emitting a warning about taking the address of a reference.
8811 static bool CheckForReference(Sema &SemaRef, const Expr *E,
8812                               const PartialDiagnostic &PD) {
8813   E = E->IgnoreParenImpCasts();
8814
8815   const FunctionDecl *FD = nullptr;
8816
8817   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8818     if (!DRE->getDecl()->getType()->isReferenceType())
8819       return false;
8820   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8821     if (!M->getMemberDecl()->getType()->isReferenceType())
8822       return false;
8823   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8824     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
8825       return false;
8826     FD = Call->getDirectCallee();
8827   } else {
8828     return false;
8829   }
8830
8831   SemaRef.Diag(E->getExprLoc(), PD);
8832
8833   // If possible, point to location of function.
8834   if (FD) {
8835     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8836   }
8837
8838   return true;
8839 }
8840
8841 // Returns true if the SourceLocation is expanded from any macro body.
8842 // Returns false if the SourceLocation is invalid, is from not in a macro
8843 // expansion, or is from expanded from a top-level macro argument.
8844 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8845   if (Loc.isInvalid())
8846     return false;
8847
8848   while (Loc.isMacroID()) {
8849     if (SM.isMacroBodyExpansion(Loc))
8850       return true;
8851     Loc = SM.getImmediateMacroCallerLoc(Loc);
8852   }
8853
8854   return false;
8855 }
8856
8857 /// \brief Diagnose pointers that are always non-null.
8858 /// \param E the expression containing the pointer
8859 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8860 /// compared to a null pointer
8861 /// \param IsEqual True when the comparison is equal to a null pointer
8862 /// \param Range Extra SourceRange to highlight in the diagnostic
8863 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8864                                         Expr::NullPointerConstantKind NullKind,
8865                                         bool IsEqual, SourceRange Range) {
8866   if (!E)
8867     return;
8868
8869   // Don't warn inside macros.
8870   if (E->getExprLoc().isMacroID()) {
8871     const SourceManager &SM = getSourceManager();
8872     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8873         IsInAnyMacroBody(SM, Range.getBegin()))
8874       return;
8875   }
8876   E = E->IgnoreImpCasts();
8877
8878   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8879
8880   if (isa<CXXThisExpr>(E)) {
8881     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8882                                 : diag::warn_this_bool_conversion;
8883     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8884     return;
8885   }
8886
8887   bool IsAddressOf = false;
8888
8889   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8890     if (UO->getOpcode() != UO_AddrOf)
8891       return;
8892     IsAddressOf = true;
8893     E = UO->getSubExpr();
8894   }
8895
8896   if (IsAddressOf) {
8897     unsigned DiagID = IsCompare
8898                           ? diag::warn_address_of_reference_null_compare
8899                           : diag::warn_address_of_reference_bool_conversion;
8900     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8901                                          << IsEqual;
8902     if (CheckForReference(*this, E, PD)) {
8903       return;
8904     }
8905   }
8906
8907   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8908     bool IsParam = isa<NonNullAttr>(NonnullAttr);
8909     std::string Str;
8910     llvm::raw_string_ostream S(Str);
8911     E->printPretty(S, nullptr, getPrintingPolicy());
8912     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8913                                 : diag::warn_cast_nonnull_to_bool;
8914     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8915       << E->getSourceRange() << Range << IsEqual;
8916     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
8917   };
8918
8919   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8920   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8921     if (auto *Callee = Call->getDirectCallee()) {
8922       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8923         ComplainAboutNonnullParamOrCall(A);
8924         return;
8925       }
8926     }
8927   }
8928
8929   // Expect to find a single Decl.  Skip anything more complicated.
8930   ValueDecl *D = nullptr;
8931   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8932     D = R->getDecl();
8933   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8934     D = M->getMemberDecl();
8935   }
8936
8937   // Weak Decls can be null.
8938   if (!D || D->isWeak())
8939     return;
8940
8941   // Check for parameter decl with nonnull attribute
8942   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8943     if (getCurFunction() &&
8944         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8945       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8946         ComplainAboutNonnullParamOrCall(A);
8947         return;
8948       }
8949
8950       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8951         auto ParamIter = llvm::find(FD->parameters(), PV);
8952         assert(ParamIter != FD->param_end());
8953         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8954
8955         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8956           if (!NonNull->args_size()) {
8957               ComplainAboutNonnullParamOrCall(NonNull);
8958               return;
8959           }
8960
8961           for (unsigned ArgNo : NonNull->args()) {
8962             if (ArgNo == ParamNo) {
8963               ComplainAboutNonnullParamOrCall(NonNull);
8964               return;
8965             }
8966           }
8967         }
8968       }
8969     }
8970   }
8971
8972   QualType T = D->getType();
8973   const bool IsArray = T->isArrayType();
8974   const bool IsFunction = T->isFunctionType();
8975
8976   // Address of function is used to silence the function warning.
8977   if (IsAddressOf && IsFunction) {
8978     return;
8979   }
8980
8981   // Found nothing.
8982   if (!IsAddressOf && !IsFunction && !IsArray)
8983     return;
8984
8985   // Pretty print the expression for the diagnostic.
8986   std::string Str;
8987   llvm::raw_string_ostream S(Str);
8988   E->printPretty(S, nullptr, getPrintingPolicy());
8989
8990   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8991                               : diag::warn_impcast_pointer_to_bool;
8992   enum {
8993     AddressOf,
8994     FunctionPointer,
8995     ArrayPointer
8996   } DiagType;
8997   if (IsAddressOf)
8998     DiagType = AddressOf;
8999   else if (IsFunction)
9000     DiagType = FunctionPointer;
9001   else if (IsArray)
9002     DiagType = ArrayPointer;
9003   else
9004     llvm_unreachable("Could not determine diagnostic.");
9005   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9006                                 << Range << IsEqual;
9007
9008   if (!IsFunction)
9009     return;
9010
9011   // Suggest '&' to silence the function warning.
9012   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9013       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9014
9015   // Check to see if '()' fixit should be emitted.
9016   QualType ReturnType;
9017   UnresolvedSet<4> NonTemplateOverloads;
9018   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9019   if (ReturnType.isNull())
9020     return;
9021
9022   if (IsCompare) {
9023     // There are two cases here.  If there is null constant, the only suggest
9024     // for a pointer return type.  If the null is 0, then suggest if the return
9025     // type is a pointer or an integer type.
9026     if (!ReturnType->isPointerType()) {
9027       if (NullKind == Expr::NPCK_ZeroExpression ||
9028           NullKind == Expr::NPCK_ZeroLiteral) {
9029         if (!ReturnType->isIntegerType())
9030           return;
9031       } else {
9032         return;
9033       }
9034     }
9035   } else { // !IsCompare
9036     // For function to bool, only suggest if the function pointer has bool
9037     // return type.
9038     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9039       return;
9040   }
9041   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9042       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9043 }
9044
9045 /// Diagnoses "dangerous" implicit conversions within the given
9046 /// expression (which is a full expression).  Implements -Wconversion
9047 /// and -Wsign-compare.
9048 ///
9049 /// \param CC the "context" location of the implicit conversion, i.e.
9050 ///   the most location of the syntactic entity requiring the implicit
9051 ///   conversion
9052 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9053   // Don't diagnose in unevaluated contexts.
9054   if (isUnevaluatedContext())
9055     return;
9056
9057   // Don't diagnose for value- or type-dependent expressions.
9058   if (E->isTypeDependent() || E->isValueDependent())
9059     return;
9060
9061   // Check for array bounds violations in cases where the check isn't triggered
9062   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9063   // ArraySubscriptExpr is on the RHS of a variable initialization.
9064   CheckArrayAccess(E);
9065
9066   // This is not the right CC for (e.g.) a variable initialization.
9067   AnalyzeImplicitConversions(*this, E, CC);
9068 }
9069
9070 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9071 /// Input argument E is a logical expression.
9072 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9073   ::CheckBoolLikeConversion(*this, E, CC);
9074 }
9075
9076 /// Diagnose when expression is an integer constant expression and its evaluation
9077 /// results in integer overflow
9078 void Sema::CheckForIntOverflow (Expr *E) {
9079   // Use a work list to deal with nested struct initializers.
9080   SmallVector<Expr *, 2> Exprs(1, E);
9081
9082   do {
9083     Expr *E = Exprs.pop_back_val();
9084
9085     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9086       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9087       continue;
9088     }
9089
9090     if (auto InitList = dyn_cast<InitListExpr>(E))
9091       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9092   } while (!Exprs.empty());
9093 }
9094
9095 namespace {
9096 /// \brief Visitor for expressions which looks for unsequenced operations on the
9097 /// same object.
9098 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9099   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9100
9101   /// \brief A tree of sequenced regions within an expression. Two regions are
9102   /// unsequenced if one is an ancestor or a descendent of the other. When we
9103   /// finish processing an expression with sequencing, such as a comma
9104   /// expression, we fold its tree nodes into its parent, since they are
9105   /// unsequenced with respect to nodes we will visit later.
9106   class SequenceTree {
9107     struct Value {
9108       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9109       unsigned Parent : 31;
9110       unsigned Merged : 1;
9111     };
9112     SmallVector<Value, 8> Values;
9113
9114   public:
9115     /// \brief A region within an expression which may be sequenced with respect
9116     /// to some other region.
9117     class Seq {
9118       explicit Seq(unsigned N) : Index(N) {}
9119       unsigned Index;
9120       friend class SequenceTree;
9121     public:
9122       Seq() : Index(0) {}
9123     };
9124
9125     SequenceTree() { Values.push_back(Value(0)); }
9126     Seq root() const { return Seq(0); }
9127
9128     /// \brief Create a new sequence of operations, which is an unsequenced
9129     /// subset of \p Parent. This sequence of operations is sequenced with
9130     /// respect to other children of \p Parent.
9131     Seq allocate(Seq Parent) {
9132       Values.push_back(Value(Parent.Index));
9133       return Seq(Values.size() - 1);
9134     }
9135
9136     /// \brief Merge a sequence of operations into its parent.
9137     void merge(Seq S) {
9138       Values[S.Index].Merged = true;
9139     }
9140
9141     /// \brief Determine whether two operations are unsequenced. This operation
9142     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9143     /// should have been merged into its parent as appropriate.
9144     bool isUnsequenced(Seq Cur, Seq Old) {
9145       unsigned C = representative(Cur.Index);
9146       unsigned Target = representative(Old.Index);
9147       while (C >= Target) {
9148         if (C == Target)
9149           return true;
9150         C = Values[C].Parent;
9151       }
9152       return false;
9153     }
9154
9155   private:
9156     /// \brief Pick a representative for a sequence.
9157     unsigned representative(unsigned K) {
9158       if (Values[K].Merged)
9159         // Perform path compression as we go.
9160         return Values[K].Parent = representative(Values[K].Parent);
9161       return K;
9162     }
9163   };
9164
9165   /// An object for which we can track unsequenced uses.
9166   typedef NamedDecl *Object;
9167
9168   /// Different flavors of object usage which we track. We only track the
9169   /// least-sequenced usage of each kind.
9170   enum UsageKind {
9171     /// A read of an object. Multiple unsequenced reads are OK.
9172     UK_Use,
9173     /// A modification of an object which is sequenced before the value
9174     /// computation of the expression, such as ++n in C++.
9175     UK_ModAsValue,
9176     /// A modification of an object which is not sequenced before the value
9177     /// computation of the expression, such as n++.
9178     UK_ModAsSideEffect,
9179
9180     UK_Count = UK_ModAsSideEffect + 1
9181   };
9182
9183   struct Usage {
9184     Usage() : Use(nullptr), Seq() {}
9185     Expr *Use;
9186     SequenceTree::Seq Seq;
9187   };
9188
9189   struct UsageInfo {
9190     UsageInfo() : Diagnosed(false) {}
9191     Usage Uses[UK_Count];
9192     /// Have we issued a diagnostic for this variable already?
9193     bool Diagnosed;
9194   };
9195   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9196
9197   Sema &SemaRef;
9198   /// Sequenced regions within the expression.
9199   SequenceTree Tree;
9200   /// Declaration modifications and references which we have seen.
9201   UsageInfoMap UsageMap;
9202   /// The region we are currently within.
9203   SequenceTree::Seq Region;
9204   /// Filled in with declarations which were modified as a side-effect
9205   /// (that is, post-increment operations).
9206   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9207   /// Expressions to check later. We defer checking these to reduce
9208   /// stack usage.
9209   SmallVectorImpl<Expr *> &WorkList;
9210
9211   /// RAII object wrapping the visitation of a sequenced subexpression of an
9212   /// expression. At the end of this process, the side-effects of the evaluation
9213   /// become sequenced with respect to the value computation of the result, so
9214   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9215   /// UK_ModAsValue.
9216   struct SequencedSubexpression {
9217     SequencedSubexpression(SequenceChecker &Self)
9218       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9219       Self.ModAsSideEffect = &ModAsSideEffect;
9220     }
9221     ~SequencedSubexpression() {
9222       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9223         UsageInfo &U = Self.UsageMap[M.first];
9224         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9225         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9226         SideEffectUsage = M.second;
9227       }
9228       Self.ModAsSideEffect = OldModAsSideEffect;
9229     }
9230
9231     SequenceChecker &Self;
9232     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9233     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9234   };
9235
9236   /// RAII object wrapping the visitation of a subexpression which we might
9237   /// choose to evaluate as a constant. If any subexpression is evaluated and
9238   /// found to be non-constant, this allows us to suppress the evaluation of
9239   /// the outer expression.
9240   class EvaluationTracker {
9241   public:
9242     EvaluationTracker(SequenceChecker &Self)
9243         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9244       Self.EvalTracker = this;
9245     }
9246     ~EvaluationTracker() {
9247       Self.EvalTracker = Prev;
9248       if (Prev)
9249         Prev->EvalOK &= EvalOK;
9250     }
9251
9252     bool evaluate(const Expr *E, bool &Result) {
9253       if (!EvalOK || E->isValueDependent())
9254         return false;
9255       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9256       return EvalOK;
9257     }
9258
9259   private:
9260     SequenceChecker &Self;
9261     EvaluationTracker *Prev;
9262     bool EvalOK;
9263   } *EvalTracker;
9264
9265   /// \brief Find the object which is produced by the specified expression,
9266   /// if any.
9267   Object getObject(Expr *E, bool Mod) const {
9268     E = E->IgnoreParenCasts();
9269     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9270       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9271         return getObject(UO->getSubExpr(), Mod);
9272     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9273       if (BO->getOpcode() == BO_Comma)
9274         return getObject(BO->getRHS(), Mod);
9275       if (Mod && BO->isAssignmentOp())
9276         return getObject(BO->getLHS(), Mod);
9277     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9278       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9279       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9280         return ME->getMemberDecl();
9281     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9282       // FIXME: If this is a reference, map through to its value.
9283       return DRE->getDecl();
9284     return nullptr;
9285   }
9286
9287   /// \brief Note that an object was modified or used by an expression.
9288   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9289     Usage &U = UI.Uses[UK];
9290     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9291       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9292         ModAsSideEffect->push_back(std::make_pair(O, U));
9293       U.Use = Ref;
9294       U.Seq = Region;
9295     }
9296   }
9297   /// \brief Check whether a modification or use conflicts with a prior usage.
9298   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9299                   bool IsModMod) {
9300     if (UI.Diagnosed)
9301       return;
9302
9303     const Usage &U = UI.Uses[OtherKind];
9304     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9305       return;
9306
9307     Expr *Mod = U.Use;
9308     Expr *ModOrUse = Ref;
9309     if (OtherKind == UK_Use)
9310       std::swap(Mod, ModOrUse);
9311
9312     SemaRef.Diag(Mod->getExprLoc(),
9313                  IsModMod ? diag::warn_unsequenced_mod_mod
9314                           : diag::warn_unsequenced_mod_use)
9315       << O << SourceRange(ModOrUse->getExprLoc());
9316     UI.Diagnosed = true;
9317   }
9318
9319   void notePreUse(Object O, Expr *Use) {
9320     UsageInfo &U = UsageMap[O];
9321     // Uses conflict with other modifications.
9322     checkUsage(O, U, Use, UK_ModAsValue, false);
9323   }
9324   void notePostUse(Object O, Expr *Use) {
9325     UsageInfo &U = UsageMap[O];
9326     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9327     addUsage(U, O, Use, UK_Use);
9328   }
9329
9330   void notePreMod(Object O, Expr *Mod) {
9331     UsageInfo &U = UsageMap[O];
9332     // Modifications conflict with other modifications and with uses.
9333     checkUsage(O, U, Mod, UK_ModAsValue, true);
9334     checkUsage(O, U, Mod, UK_Use, false);
9335   }
9336   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9337     UsageInfo &U = UsageMap[O];
9338     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9339     addUsage(U, O, Use, UK);
9340   }
9341
9342 public:
9343   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9344       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9345         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9346     Visit(E);
9347   }
9348
9349   void VisitStmt(Stmt *S) {
9350     // Skip all statements which aren't expressions for now.
9351   }
9352
9353   void VisitExpr(Expr *E) {
9354     // By default, just recurse to evaluated subexpressions.
9355     Base::VisitStmt(E);
9356   }
9357
9358   void VisitCastExpr(CastExpr *E) {
9359     Object O = Object();
9360     if (E->getCastKind() == CK_LValueToRValue)
9361       O = getObject(E->getSubExpr(), false);
9362
9363     if (O)
9364       notePreUse(O, E);
9365     VisitExpr(E);
9366     if (O)
9367       notePostUse(O, E);
9368   }
9369
9370   void VisitBinComma(BinaryOperator *BO) {
9371     // C++11 [expr.comma]p1:
9372     //   Every value computation and side effect associated with the left
9373     //   expression is sequenced before every value computation and side
9374     //   effect associated with the right expression.
9375     SequenceTree::Seq LHS = Tree.allocate(Region);
9376     SequenceTree::Seq RHS = Tree.allocate(Region);
9377     SequenceTree::Seq OldRegion = Region;
9378
9379     {
9380       SequencedSubexpression SeqLHS(*this);
9381       Region = LHS;
9382       Visit(BO->getLHS());
9383     }
9384
9385     Region = RHS;
9386     Visit(BO->getRHS());
9387
9388     Region = OldRegion;
9389
9390     // Forget that LHS and RHS are sequenced. They are both unsequenced
9391     // with respect to other stuff.
9392     Tree.merge(LHS);
9393     Tree.merge(RHS);
9394   }
9395
9396   void VisitBinAssign(BinaryOperator *BO) {
9397     // The modification is sequenced after the value computation of the LHS
9398     // and RHS, so check it before inspecting the operands and update the
9399     // map afterwards.
9400     Object O = getObject(BO->getLHS(), true);
9401     if (!O)
9402       return VisitExpr(BO);
9403
9404     notePreMod(O, BO);
9405
9406     // C++11 [expr.ass]p7:
9407     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9408     //   only once.
9409     //
9410     // Therefore, for a compound assignment operator, O is considered used
9411     // everywhere except within the evaluation of E1 itself.
9412     if (isa<CompoundAssignOperator>(BO))
9413       notePreUse(O, BO);
9414
9415     Visit(BO->getLHS());
9416
9417     if (isa<CompoundAssignOperator>(BO))
9418       notePostUse(O, BO);
9419
9420     Visit(BO->getRHS());
9421
9422     // C++11 [expr.ass]p1:
9423     //   the assignment is sequenced [...] before the value computation of the
9424     //   assignment expression.
9425     // C11 6.5.16/3 has no such rule.
9426     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9427                                                        : UK_ModAsSideEffect);
9428   }
9429
9430   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9431     VisitBinAssign(CAO);
9432   }
9433
9434   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9435   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9436   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9437     Object O = getObject(UO->getSubExpr(), true);
9438     if (!O)
9439       return VisitExpr(UO);
9440
9441     notePreMod(O, UO);
9442     Visit(UO->getSubExpr());
9443     // C++11 [expr.pre.incr]p1:
9444     //   the expression ++x is equivalent to x+=1
9445     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9446                                                        : UK_ModAsSideEffect);
9447   }
9448
9449   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9450   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9451   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9452     Object O = getObject(UO->getSubExpr(), true);
9453     if (!O)
9454       return VisitExpr(UO);
9455
9456     notePreMod(O, UO);
9457     Visit(UO->getSubExpr());
9458     notePostMod(O, UO, UK_ModAsSideEffect);
9459   }
9460
9461   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9462   void VisitBinLOr(BinaryOperator *BO) {
9463     // The side-effects of the LHS of an '&&' are sequenced before the
9464     // value computation of the RHS, and hence before the value computation
9465     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9466     // as if they were unconditionally sequenced.
9467     EvaluationTracker Eval(*this);
9468     {
9469       SequencedSubexpression Sequenced(*this);
9470       Visit(BO->getLHS());
9471     }
9472
9473     bool Result;
9474     if (Eval.evaluate(BO->getLHS(), Result)) {
9475       if (!Result)
9476         Visit(BO->getRHS());
9477     } else {
9478       // Check for unsequenced operations in the RHS, treating it as an
9479       // entirely separate evaluation.
9480       //
9481       // FIXME: If there are operations in the RHS which are unsequenced
9482       // with respect to operations outside the RHS, and those operations
9483       // are unconditionally evaluated, diagnose them.
9484       WorkList.push_back(BO->getRHS());
9485     }
9486   }
9487   void VisitBinLAnd(BinaryOperator *BO) {
9488     EvaluationTracker Eval(*this);
9489     {
9490       SequencedSubexpression Sequenced(*this);
9491       Visit(BO->getLHS());
9492     }
9493
9494     bool Result;
9495     if (Eval.evaluate(BO->getLHS(), Result)) {
9496       if (Result)
9497         Visit(BO->getRHS());
9498     } else {
9499       WorkList.push_back(BO->getRHS());
9500     }
9501   }
9502
9503   // Only visit the condition, unless we can be sure which subexpression will
9504   // be chosen.
9505   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
9506     EvaluationTracker Eval(*this);
9507     {
9508       SequencedSubexpression Sequenced(*this);
9509       Visit(CO->getCond());
9510     }
9511
9512     bool Result;
9513     if (Eval.evaluate(CO->getCond(), Result))
9514       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
9515     else {
9516       WorkList.push_back(CO->getTrueExpr());
9517       WorkList.push_back(CO->getFalseExpr());
9518     }
9519   }
9520
9521   void VisitCallExpr(CallExpr *CE) {
9522     // C++11 [intro.execution]p15:
9523     //   When calling a function [...], every value computation and side effect
9524     //   associated with any argument expression, or with the postfix expression
9525     //   designating the called function, is sequenced before execution of every
9526     //   expression or statement in the body of the function [and thus before
9527     //   the value computation of its result].
9528     SequencedSubexpression Sequenced(*this);
9529     Base::VisitCallExpr(CE);
9530
9531     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9532   }
9533
9534   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
9535     // This is a call, so all subexpressions are sequenced before the result.
9536     SequencedSubexpression Sequenced(*this);
9537
9538     if (!CCE->isListInitialization())
9539       return VisitExpr(CCE);
9540
9541     // In C++11, list initializations are sequenced.
9542     SmallVector<SequenceTree::Seq, 32> Elts;
9543     SequenceTree::Seq Parent = Region;
9544     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9545                                         E = CCE->arg_end();
9546          I != E; ++I) {
9547       Region = Tree.allocate(Parent);
9548       Elts.push_back(Region);
9549       Visit(*I);
9550     }
9551
9552     // Forget that the initializers are sequenced.
9553     Region = Parent;
9554     for (unsigned I = 0; I < Elts.size(); ++I)
9555       Tree.merge(Elts[I]);
9556   }
9557
9558   void VisitInitListExpr(InitListExpr *ILE) {
9559     if (!SemaRef.getLangOpts().CPlusPlus11)
9560       return VisitExpr(ILE);
9561
9562     // In C++11, list initializations are sequenced.
9563     SmallVector<SequenceTree::Seq, 32> Elts;
9564     SequenceTree::Seq Parent = Region;
9565     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9566       Expr *E = ILE->getInit(I);
9567       if (!E) continue;
9568       Region = Tree.allocate(Parent);
9569       Elts.push_back(Region);
9570       Visit(E);
9571     }
9572
9573     // Forget that the initializers are sequenced.
9574     Region = Parent;
9575     for (unsigned I = 0; I < Elts.size(); ++I)
9576       Tree.merge(Elts[I]);
9577   }
9578 };
9579 } // end anonymous namespace
9580
9581 void Sema::CheckUnsequencedOperations(Expr *E) {
9582   SmallVector<Expr *, 8> WorkList;
9583   WorkList.push_back(E);
9584   while (!WorkList.empty()) {
9585     Expr *Item = WorkList.pop_back_val();
9586     SequenceChecker(*this, Item, WorkList);
9587   }
9588 }
9589
9590 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9591                               bool IsConstexpr) {
9592   CheckImplicitConversions(E, CheckLoc);
9593   if (!E->isInstantiationDependent())
9594     CheckUnsequencedOperations(E);
9595   if (!IsConstexpr && !E->isValueDependent())
9596     CheckForIntOverflow(E);
9597 }
9598
9599 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9600                                        FieldDecl *BitField,
9601                                        Expr *Init) {
9602   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9603 }
9604
9605 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9606                                          SourceLocation Loc) {
9607   if (!PType->isVariablyModifiedType())
9608     return;
9609   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9610     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9611     return;
9612   }
9613   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9614     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9615     return;
9616   }
9617   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9618     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9619     return;
9620   }
9621
9622   const ArrayType *AT = S.Context.getAsArrayType(PType);
9623   if (!AT)
9624     return;
9625
9626   if (AT->getSizeModifier() != ArrayType::Star) {
9627     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9628     return;
9629   }
9630
9631   S.Diag(Loc, diag::err_array_star_in_function_definition);
9632 }
9633
9634 /// CheckParmsForFunctionDef - Check that the parameters of the given
9635 /// function are appropriate for the definition of a function. This
9636 /// takes care of any checks that cannot be performed on the
9637 /// declaration itself, e.g., that the types of each of the function
9638 /// parameters are complete.
9639 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
9640                                     bool CheckParameterNames) {
9641   bool HasInvalidParm = false;
9642   for (ParmVarDecl *Param : Parameters) {
9643     // C99 6.7.5.3p4: the parameters in a parameter type list in a
9644     // function declarator that is part of a function definition of
9645     // that function shall not have incomplete type.
9646     //
9647     // This is also C++ [dcl.fct]p6.
9648     if (!Param->isInvalidDecl() &&
9649         RequireCompleteType(Param->getLocation(), Param->getType(),
9650                             diag::err_typecheck_decl_incomplete_type)) {
9651       Param->setInvalidDecl();
9652       HasInvalidParm = true;
9653     }
9654
9655     // C99 6.9.1p5: If the declarator includes a parameter type list, the
9656     // declaration of each parameter shall include an identifier.
9657     if (CheckParameterNames &&
9658         Param->getIdentifier() == nullptr &&
9659         !Param->isImplicit() &&
9660         !getLangOpts().CPlusPlus)
9661       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9662
9663     // C99 6.7.5.3p12:
9664     //   If the function declarator is not part of a definition of that
9665     //   function, parameters may have incomplete type and may use the [*]
9666     //   notation in their sequences of declarator specifiers to specify
9667     //   variable length array types.
9668     QualType PType = Param->getOriginalType();
9669     // FIXME: This diagnostic should point the '[*]' if source-location
9670     // information is added for it.
9671     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
9672
9673     // MSVC destroys objects passed by value in the callee.  Therefore a
9674     // function definition which takes such a parameter must be able to call the
9675     // object's destructor.  However, we don't perform any direct access check
9676     // on the dtor.
9677     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9678                                        .getCXXABI()
9679                                        .areArgsDestroyedLeftToRightInCallee()) {
9680       if (!Param->isInvalidDecl()) {
9681         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9682           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9683           if (!ClassDecl->isInvalidDecl() &&
9684               !ClassDecl->hasIrrelevantDestructor() &&
9685               !ClassDecl->isDependentContext()) {
9686             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9687             MarkFunctionReferenced(Param->getLocation(), Destructor);
9688             DiagnoseUseOfDecl(Destructor, Param->getLocation());
9689           }
9690         }
9691       }
9692     }
9693
9694     // Parameters with the pass_object_size attribute only need to be marked
9695     // constant at function definitions. Because we lack information about
9696     // whether we're on a declaration or definition when we're instantiating the
9697     // attribute, we need to check for constness here.
9698     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9699       if (!Param->getType().isConstQualified())
9700         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9701             << Attr->getSpelling() << 1;
9702   }
9703
9704   return HasInvalidParm;
9705 }
9706
9707 /// CheckCastAlign - Implements -Wcast-align, which warns when a
9708 /// pointer cast increases the alignment requirements.
9709 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9710   // This is actually a lot of work to potentially be doing on every
9711   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
9712   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
9713     return;
9714
9715   // Ignore dependent types.
9716   if (T->isDependentType() || Op->getType()->isDependentType())
9717     return;
9718
9719   // Require that the destination be a pointer type.
9720   const PointerType *DestPtr = T->getAs<PointerType>();
9721   if (!DestPtr) return;
9722
9723   // If the destination has alignment 1, we're done.
9724   QualType DestPointee = DestPtr->getPointeeType();
9725   if (DestPointee->isIncompleteType()) return;
9726   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9727   if (DestAlign.isOne()) return;
9728
9729   // Require that the source be a pointer type.
9730   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9731   if (!SrcPtr) return;
9732   QualType SrcPointee = SrcPtr->getPointeeType();
9733
9734   // Whitelist casts from cv void*.  We already implicitly
9735   // whitelisted casts to cv void*, since they have alignment 1.
9736   // Also whitelist casts involving incomplete types, which implicitly
9737   // includes 'void'.
9738   if (SrcPointee->isIncompleteType()) return;
9739
9740   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9741   if (SrcAlign >= DestAlign) return;
9742
9743   Diag(TRange.getBegin(), diag::warn_cast_align)
9744     << Op->getType() << T
9745     << static_cast<unsigned>(SrcAlign.getQuantity())
9746     << static_cast<unsigned>(DestAlign.getQuantity())
9747     << TRange << Op->getSourceRange();
9748 }
9749
9750 /// \brief Check whether this array fits the idiom of a size-one tail padded
9751 /// array member of a struct.
9752 ///
9753 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
9754 /// commonly used to emulate flexible arrays in C89 code.
9755 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
9756                                     const NamedDecl *ND) {
9757   if (Size != 1 || !ND) return false;
9758
9759   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9760   if (!FD) return false;
9761
9762   // Don't consider sizes resulting from macro expansions or template argument
9763   // substitution to form C89 tail-padded arrays.
9764
9765   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
9766   while (TInfo) {
9767     TypeLoc TL = TInfo->getTypeLoc();
9768     // Look through typedefs.
9769     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9770       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
9771       TInfo = TDL->getTypeSourceInfo();
9772       continue;
9773     }
9774     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9775       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
9776       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9777         return false;
9778     }
9779     break;
9780   }
9781
9782   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
9783   if (!RD) return false;
9784   if (RD->isUnion()) return false;
9785   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9786     if (!CRD->isStandardLayout()) return false;
9787   }
9788
9789   // See if this is the last field decl in the record.
9790   const Decl *D = FD;
9791   while ((D = D->getNextDeclInContext()))
9792     if (isa<FieldDecl>(D))
9793       return false;
9794   return true;
9795 }
9796
9797 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9798                             const ArraySubscriptExpr *ASE,
9799                             bool AllowOnePastEnd, bool IndexNegated) {
9800   IndexExpr = IndexExpr->IgnoreParenImpCasts();
9801   if (IndexExpr->isValueDependent())
9802     return;
9803
9804   const Type *EffectiveType =
9805       BaseExpr->getType()->getPointeeOrArrayElementType();
9806   BaseExpr = BaseExpr->IgnoreParenCasts();
9807   const ConstantArrayType *ArrayTy =
9808     Context.getAsConstantArrayType(BaseExpr->getType());
9809   if (!ArrayTy)
9810     return;
9811
9812   llvm::APSInt index;
9813   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
9814     return;
9815   if (IndexNegated)
9816     index = -index;
9817
9818   const NamedDecl *ND = nullptr;
9819   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9820     ND = dyn_cast<NamedDecl>(DRE->getDecl());
9821   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9822     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9823
9824   if (index.isUnsigned() || !index.isNegative()) {
9825     llvm::APInt size = ArrayTy->getSize();
9826     if (!size.isStrictlyPositive())
9827       return;
9828
9829     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
9830     if (BaseType != EffectiveType) {
9831       // Make sure we're comparing apples to apples when comparing index to size
9832       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9833       uint64_t array_typesize = Context.getTypeSize(BaseType);
9834       // Handle ptrarith_typesize being zero, such as when casting to void*
9835       if (!ptrarith_typesize) ptrarith_typesize = 1;
9836       if (ptrarith_typesize != array_typesize) {
9837         // There's a cast to a different size type involved
9838         uint64_t ratio = array_typesize / ptrarith_typesize;
9839         // TODO: Be smarter about handling cases where array_typesize is not a
9840         // multiple of ptrarith_typesize
9841         if (ptrarith_typesize * ratio == array_typesize)
9842           size *= llvm::APInt(size.getBitWidth(), ratio);
9843       }
9844     }
9845
9846     if (size.getBitWidth() > index.getBitWidth())
9847       index = index.zext(size.getBitWidth());
9848     else if (size.getBitWidth() < index.getBitWidth())
9849       size = size.zext(index.getBitWidth());
9850
9851     // For array subscripting the index must be less than size, but for pointer
9852     // arithmetic also allow the index (offset) to be equal to size since
9853     // computing the next address after the end of the array is legal and
9854     // commonly done e.g. in C++ iterators and range-based for loops.
9855     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
9856       return;
9857
9858     // Also don't warn for arrays of size 1 which are members of some
9859     // structure. These are often used to approximate flexible arrays in C89
9860     // code.
9861     if (IsTailPaddedMemberArray(*this, size, ND))
9862       return;
9863
9864     // Suppress the warning if the subscript expression (as identified by the
9865     // ']' location) and the index expression are both from macro expansions
9866     // within a system header.
9867     if (ASE) {
9868       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9869           ASE->getRBracketLoc());
9870       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9871         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9872             IndexExpr->getLocStart());
9873         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
9874           return;
9875       }
9876     }
9877
9878     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
9879     if (ASE)
9880       DiagID = diag::warn_array_index_exceeds_bounds;
9881
9882     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9883                         PDiag(DiagID) << index.toString(10, true)
9884                           << size.toString(10, true)
9885                           << (unsigned)size.getLimitedValue(~0U)
9886                           << IndexExpr->getSourceRange());
9887   } else {
9888     unsigned DiagID = diag::warn_array_index_precedes_bounds;
9889     if (!ASE) {
9890       DiagID = diag::warn_ptr_arith_precedes_bounds;
9891       if (index.isNegative()) index = -index;
9892     }
9893
9894     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9895                         PDiag(DiagID) << index.toString(10, true)
9896                           << IndexExpr->getSourceRange());
9897   }
9898
9899   if (!ND) {
9900     // Try harder to find a NamedDecl to point at in the note.
9901     while (const ArraySubscriptExpr *ASE =
9902            dyn_cast<ArraySubscriptExpr>(BaseExpr))
9903       BaseExpr = ASE->getBase()->IgnoreParenCasts();
9904     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9905       ND = dyn_cast<NamedDecl>(DRE->getDecl());
9906     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9907       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9908   }
9909
9910   if (ND)
9911     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9912                         PDiag(diag::note_array_index_out_of_bounds)
9913                           << ND->getDeclName());
9914 }
9915
9916 void Sema::CheckArrayAccess(const Expr *expr) {
9917   int AllowOnePastEnd = 0;
9918   while (expr) {
9919     expr = expr->IgnoreParenImpCasts();
9920     switch (expr->getStmtClass()) {
9921       case Stmt::ArraySubscriptExprClass: {
9922         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
9923         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
9924                          AllowOnePastEnd > 0);
9925         return;
9926       }
9927       case Stmt::OMPArraySectionExprClass: {
9928         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9929         if (ASE->getLowerBound())
9930           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9931                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
9932         return;
9933       }
9934       case Stmt::UnaryOperatorClass: {
9935         // Only unwrap the * and & unary operators
9936         const UnaryOperator *UO = cast<UnaryOperator>(expr);
9937         expr = UO->getSubExpr();
9938         switch (UO->getOpcode()) {
9939           case UO_AddrOf:
9940             AllowOnePastEnd++;
9941             break;
9942           case UO_Deref:
9943             AllowOnePastEnd--;
9944             break;
9945           default:
9946             return;
9947         }
9948         break;
9949       }
9950       case Stmt::ConditionalOperatorClass: {
9951         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9952         if (const Expr *lhs = cond->getLHS())
9953           CheckArrayAccess(lhs);
9954         if (const Expr *rhs = cond->getRHS())
9955           CheckArrayAccess(rhs);
9956         return;
9957       }
9958       default:
9959         return;
9960     }
9961   }
9962 }
9963
9964 //===--- CHECK: Objective-C retain cycles ----------------------------------//
9965
9966 namespace {
9967   struct RetainCycleOwner {
9968     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
9969     VarDecl *Variable;
9970     SourceRange Range;
9971     SourceLocation Loc;
9972     bool Indirect;
9973
9974     void setLocsFrom(Expr *e) {
9975       Loc = e->getExprLoc();
9976       Range = e->getSourceRange();
9977     }
9978   };
9979 } // end anonymous namespace
9980
9981 /// Consider whether capturing the given variable can possibly lead to
9982 /// a retain cycle.
9983 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
9984   // In ARC, it's captured strongly iff the variable has __strong
9985   // lifetime.  In MRR, it's captured strongly if the variable is
9986   // __block and has an appropriate type.
9987   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9988     return false;
9989
9990   owner.Variable = var;
9991   if (ref)
9992     owner.setLocsFrom(ref);
9993   return true;
9994 }
9995
9996 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
9997   while (true) {
9998     e = e->IgnoreParens();
9999     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10000       switch (cast->getCastKind()) {
10001       case CK_BitCast:
10002       case CK_LValueBitCast:
10003       case CK_LValueToRValue:
10004       case CK_ARCReclaimReturnedObject:
10005         e = cast->getSubExpr();
10006         continue;
10007
10008       default:
10009         return false;
10010       }
10011     }
10012
10013     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10014       ObjCIvarDecl *ivar = ref->getDecl();
10015       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10016         return false;
10017
10018       // Try to find a retain cycle in the base.
10019       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10020         return false;
10021
10022       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10023       owner.Indirect = true;
10024       return true;
10025     }
10026
10027     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10028       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10029       if (!var) return false;
10030       return considerVariable(var, ref, owner);
10031     }
10032
10033     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10034       if (member->isArrow()) return false;
10035
10036       // Don't count this as an indirect ownership.
10037       e = member->getBase();
10038       continue;
10039     }
10040
10041     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10042       // Only pay attention to pseudo-objects on property references.
10043       ObjCPropertyRefExpr *pre
10044         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10045                                               ->IgnoreParens());
10046       if (!pre) return false;
10047       if (pre->isImplicitProperty()) return false;
10048       ObjCPropertyDecl *property = pre->getExplicitProperty();
10049       if (!property->isRetaining() &&
10050           !(property->getPropertyIvarDecl() &&
10051             property->getPropertyIvarDecl()->getType()
10052               .getObjCLifetime() == Qualifiers::OCL_Strong))
10053           return false;
10054
10055       owner.Indirect = true;
10056       if (pre->isSuperReceiver()) {
10057         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10058         if (!owner.Variable)
10059           return false;
10060         owner.Loc = pre->getLocation();
10061         owner.Range = pre->getSourceRange();
10062         return true;
10063       }
10064       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10065                               ->getSourceExpr());
10066       continue;
10067     }
10068
10069     // Array ivars?
10070
10071     return false;
10072   }
10073 }
10074
10075 namespace {
10076   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10077     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10078       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10079         Context(Context), Variable(variable), Capturer(nullptr),
10080         VarWillBeReased(false) {}
10081     ASTContext &Context;
10082     VarDecl *Variable;
10083     Expr *Capturer;
10084     bool VarWillBeReased;
10085
10086     void VisitDeclRefExpr(DeclRefExpr *ref) {
10087       if (ref->getDecl() == Variable && !Capturer)
10088         Capturer = ref;
10089     }
10090
10091     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10092       if (Capturer) return;
10093       Visit(ref->getBase());
10094       if (Capturer && ref->isFreeIvar())
10095         Capturer = ref;
10096     }
10097
10098     void VisitBlockExpr(BlockExpr *block) {
10099       // Look inside nested blocks 
10100       if (block->getBlockDecl()->capturesVariable(Variable))
10101         Visit(block->getBlockDecl()->getBody());
10102     }
10103     
10104     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10105       if (Capturer) return;
10106       if (OVE->getSourceExpr())
10107         Visit(OVE->getSourceExpr());
10108     }
10109     void VisitBinaryOperator(BinaryOperator *BinOp) {
10110       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10111         return;
10112       Expr *LHS = BinOp->getLHS();
10113       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10114         if (DRE->getDecl() != Variable)
10115           return;
10116         if (Expr *RHS = BinOp->getRHS()) {
10117           RHS = RHS->IgnoreParenCasts();
10118           llvm::APSInt Value;
10119           VarWillBeReased =
10120             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10121         }
10122       }
10123     }
10124   };
10125 } // end anonymous namespace
10126
10127 /// Check whether the given argument is a block which captures a
10128 /// variable.
10129 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10130   assert(owner.Variable && owner.Loc.isValid());
10131
10132   e = e->IgnoreParenCasts();
10133
10134   // Look through [^{...} copy] and Block_copy(^{...}).
10135   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10136     Selector Cmd = ME->getSelector();
10137     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10138       e = ME->getInstanceReceiver();
10139       if (!e)
10140         return nullptr;
10141       e = e->IgnoreParenCasts();
10142     }
10143   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10144     if (CE->getNumArgs() == 1) {
10145       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10146       if (Fn) {
10147         const IdentifierInfo *FnI = Fn->getIdentifier();
10148         if (FnI && FnI->isStr("_Block_copy")) {
10149           e = CE->getArg(0)->IgnoreParenCasts();
10150         }
10151       }
10152     }
10153   }
10154   
10155   BlockExpr *block = dyn_cast<BlockExpr>(e);
10156   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10157     return nullptr;
10158
10159   FindCaptureVisitor visitor(S.Context, owner.Variable);
10160   visitor.Visit(block->getBlockDecl()->getBody());
10161   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10162 }
10163
10164 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10165                                 RetainCycleOwner &owner) {
10166   assert(capturer);
10167   assert(owner.Variable && owner.Loc.isValid());
10168
10169   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10170     << owner.Variable << capturer->getSourceRange();
10171   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10172     << owner.Indirect << owner.Range;
10173 }
10174
10175 /// Check for a keyword selector that starts with the word 'add' or
10176 /// 'set'.
10177 static bool isSetterLikeSelector(Selector sel) {
10178   if (sel.isUnarySelector()) return false;
10179
10180   StringRef str = sel.getNameForSlot(0);
10181   while (!str.empty() && str.front() == '_') str = str.substr(1);
10182   if (str.startswith("set"))
10183     str = str.substr(3);
10184   else if (str.startswith("add")) {
10185     // Specially whitelist 'addOperationWithBlock:'.
10186     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10187       return false;
10188     str = str.substr(3);
10189   }
10190   else
10191     return false;
10192
10193   if (str.empty()) return true;
10194   return !isLowercase(str.front());
10195 }
10196
10197 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10198                                                     ObjCMessageExpr *Message) {
10199   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10200                                                 Message->getReceiverInterface(),
10201                                                 NSAPI::ClassId_NSMutableArray);
10202   if (!IsMutableArray) {
10203     return None;
10204   }
10205
10206   Selector Sel = Message->getSelector();
10207
10208   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10209     S.NSAPIObj->getNSArrayMethodKind(Sel);
10210   if (!MKOpt) {
10211     return None;
10212   }
10213
10214   NSAPI::NSArrayMethodKind MK = *MKOpt;
10215
10216   switch (MK) {
10217     case NSAPI::NSMutableArr_addObject:
10218     case NSAPI::NSMutableArr_insertObjectAtIndex:
10219     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10220       return 0;
10221     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10222       return 1;
10223
10224     default:
10225       return None;
10226   }
10227
10228   return None;
10229 }
10230
10231 static
10232 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10233                                                   ObjCMessageExpr *Message) {
10234   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10235                                             Message->getReceiverInterface(),
10236                                             NSAPI::ClassId_NSMutableDictionary);
10237   if (!IsMutableDictionary) {
10238     return None;
10239   }
10240
10241   Selector Sel = Message->getSelector();
10242
10243   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10244     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10245   if (!MKOpt) {
10246     return None;
10247   }
10248
10249   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10250
10251   switch (MK) {
10252     case NSAPI::NSMutableDict_setObjectForKey:
10253     case NSAPI::NSMutableDict_setValueForKey:
10254     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10255       return 0;
10256
10257     default:
10258       return None;
10259   }
10260
10261   return None;
10262 }
10263
10264 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10265   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10266                                                 Message->getReceiverInterface(),
10267                                                 NSAPI::ClassId_NSMutableSet);
10268
10269   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10270                                             Message->getReceiverInterface(),
10271                                             NSAPI::ClassId_NSMutableOrderedSet);
10272   if (!IsMutableSet && !IsMutableOrderedSet) {
10273     return None;
10274   }
10275
10276   Selector Sel = Message->getSelector();
10277
10278   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10279   if (!MKOpt) {
10280     return None;
10281   }
10282
10283   NSAPI::NSSetMethodKind MK = *MKOpt;
10284
10285   switch (MK) {
10286     case NSAPI::NSMutableSet_addObject:
10287     case NSAPI::NSOrderedSet_setObjectAtIndex:
10288     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10289     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10290       return 0;
10291     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10292       return 1;
10293   }
10294
10295   return None;
10296 }
10297
10298 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10299   if (!Message->isInstanceMessage()) {
10300     return;
10301   }
10302
10303   Optional<int> ArgOpt;
10304
10305   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10306       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10307       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10308     return;
10309   }
10310
10311   int ArgIndex = *ArgOpt;
10312
10313   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10314   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10315     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10316   }
10317
10318   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10319     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10320       if (ArgRE->isObjCSelfExpr()) {
10321         Diag(Message->getSourceRange().getBegin(),
10322              diag::warn_objc_circular_container)
10323           << ArgRE->getDecl()->getName() << StringRef("super");
10324       }
10325     }
10326   } else {
10327     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10328
10329     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10330       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10331     }
10332
10333     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10334       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10335         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10336           ValueDecl *Decl = ReceiverRE->getDecl();
10337           Diag(Message->getSourceRange().getBegin(),
10338                diag::warn_objc_circular_container)
10339             << Decl->getName() << Decl->getName();
10340           if (!ArgRE->isObjCSelfExpr()) {
10341             Diag(Decl->getLocation(),
10342                  diag::note_objc_circular_container_declared_here)
10343               << Decl->getName();
10344           }
10345         }
10346       }
10347     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10348       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10349         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10350           ObjCIvarDecl *Decl = IvarRE->getDecl();
10351           Diag(Message->getSourceRange().getBegin(),
10352                diag::warn_objc_circular_container)
10353             << Decl->getName() << Decl->getName();
10354           Diag(Decl->getLocation(),
10355                diag::note_objc_circular_container_declared_here)
10356             << Decl->getName();
10357         }
10358       }
10359     }
10360   }
10361 }
10362
10363 /// Check a message send to see if it's likely to cause a retain cycle.
10364 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10365   // Only check instance methods whose selector looks like a setter.
10366   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10367     return;
10368
10369   // Try to find a variable that the receiver is strongly owned by.
10370   RetainCycleOwner owner;
10371   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
10372     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10373       return;
10374   } else {
10375     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10376     owner.Variable = getCurMethodDecl()->getSelfDecl();
10377     owner.Loc = msg->getSuperLoc();
10378     owner.Range = msg->getSuperLoc();
10379   }
10380
10381   // Check whether the receiver is captured by any of the arguments.
10382   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10383     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10384       return diagnoseRetainCycle(*this, capturer, owner);
10385 }
10386
10387 /// Check a property assign to see if it's likely to cause a retain cycle.
10388 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10389   RetainCycleOwner owner;
10390   if (!findRetainCycleOwner(*this, receiver, owner))
10391     return;
10392
10393   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10394     diagnoseRetainCycle(*this, capturer, owner);
10395 }
10396
10397 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10398   RetainCycleOwner Owner;
10399   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10400     return;
10401   
10402   // Because we don't have an expression for the variable, we have to set the
10403   // location explicitly here.
10404   Owner.Loc = Var->getLocation();
10405   Owner.Range = Var->getSourceRange();
10406   
10407   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10408     diagnoseRetainCycle(*this, Capturer, Owner);
10409 }
10410
10411 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10412                                      Expr *RHS, bool isProperty) {
10413   // Check if RHS is an Objective-C object literal, which also can get
10414   // immediately zapped in a weak reference.  Note that we explicitly
10415   // allow ObjCStringLiterals, since those are designed to never really die.
10416   RHS = RHS->IgnoreParenImpCasts();
10417
10418   // This enum needs to match with the 'select' in
10419   // warn_objc_arc_literal_assign (off-by-1).
10420   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10421   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10422     return false;
10423
10424   S.Diag(Loc, diag::warn_arc_literal_assign)
10425     << (unsigned) Kind
10426     << (isProperty ? 0 : 1)
10427     << RHS->getSourceRange();
10428
10429   return true;
10430 }
10431
10432 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10433                                     Qualifiers::ObjCLifetime LT,
10434                                     Expr *RHS, bool isProperty) {
10435   // Strip off any implicit cast added to get to the one ARC-specific.
10436   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10437     if (cast->getCastKind() == CK_ARCConsumeObject) {
10438       S.Diag(Loc, diag::warn_arc_retained_assign)
10439         << (LT == Qualifiers::OCL_ExplicitNone)
10440         << (isProperty ? 0 : 1)
10441         << RHS->getSourceRange();
10442       return true;
10443     }
10444     RHS = cast->getSubExpr();
10445   }
10446
10447   if (LT == Qualifiers::OCL_Weak &&
10448       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10449     return true;
10450
10451   return false;
10452 }
10453
10454 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10455                               QualType LHS, Expr *RHS) {
10456   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10457
10458   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10459     return false;
10460
10461   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10462     return true;
10463
10464   return false;
10465 }
10466
10467 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10468                               Expr *LHS, Expr *RHS) {
10469   QualType LHSType;
10470   // PropertyRef on LHS type need be directly obtained from
10471   // its declaration as it has a PseudoType.
10472   ObjCPropertyRefExpr *PRE
10473     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10474   if (PRE && !PRE->isImplicitProperty()) {
10475     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10476     if (PD)
10477       LHSType = PD->getType();
10478   }
10479   
10480   if (LHSType.isNull())
10481     LHSType = LHS->getType();
10482
10483   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10484
10485   if (LT == Qualifiers::OCL_Weak) {
10486     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10487       getCurFunction()->markSafeWeakUse(LHS);
10488   }
10489
10490   if (checkUnsafeAssigns(Loc, LHSType, RHS))
10491     return;
10492
10493   // FIXME. Check for other life times.
10494   if (LT != Qualifiers::OCL_None)
10495     return;
10496   
10497   if (PRE) {
10498     if (PRE->isImplicitProperty())
10499       return;
10500     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10501     if (!PD)
10502       return;
10503     
10504     unsigned Attributes = PD->getPropertyAttributes();
10505     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
10506       // when 'assign' attribute was not explicitly specified
10507       // by user, ignore it and rely on property type itself
10508       // for lifetime info.
10509       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10510       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10511           LHSType->isObjCRetainableType())
10512         return;
10513         
10514       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10515         if (cast->getCastKind() == CK_ARCConsumeObject) {
10516           Diag(Loc, diag::warn_arc_retained_property_assign)
10517           << RHS->getSourceRange();
10518           return;
10519         }
10520         RHS = cast->getSubExpr();
10521       }
10522     }
10523     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
10524       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10525         return;
10526     }
10527   }
10528 }
10529
10530 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10531
10532 namespace {
10533 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10534                                  SourceLocation StmtLoc,
10535                                  const NullStmt *Body) {
10536   // Do not warn if the body is a macro that expands to nothing, e.g:
10537   //
10538   // #define CALL(x)
10539   // if (condition)
10540   //   CALL(0);
10541   //
10542   if (Body->hasLeadingEmptyMacro())
10543     return false;
10544
10545   // Get line numbers of statement and body.
10546   bool StmtLineInvalid;
10547   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
10548                                                       &StmtLineInvalid);
10549   if (StmtLineInvalid)
10550     return false;
10551
10552   bool BodyLineInvalid;
10553   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10554                                                       &BodyLineInvalid);
10555   if (BodyLineInvalid)
10556     return false;
10557
10558   // Warn if null statement and body are on the same line.
10559   if (StmtLine != BodyLine)
10560     return false;
10561
10562   return true;
10563 }
10564 } // end anonymous namespace
10565
10566 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10567                                  const Stmt *Body,
10568                                  unsigned DiagID) {
10569   // Since this is a syntactic check, don't emit diagnostic for template
10570   // instantiations, this just adds noise.
10571   if (CurrentInstantiationScope)
10572     return;
10573
10574   // The body should be a null statement.
10575   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10576   if (!NBody)
10577     return;
10578
10579   // Do the usual checks.
10580   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10581     return;
10582
10583   Diag(NBody->getSemiLoc(), DiagID);
10584   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10585 }
10586
10587 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10588                                  const Stmt *PossibleBody) {
10589   assert(!CurrentInstantiationScope); // Ensured by caller
10590
10591   SourceLocation StmtLoc;
10592   const Stmt *Body;
10593   unsigned DiagID;
10594   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10595     StmtLoc = FS->getRParenLoc();
10596     Body = FS->getBody();
10597     DiagID = diag::warn_empty_for_body;
10598   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10599     StmtLoc = WS->getCond()->getSourceRange().getEnd();
10600     Body = WS->getBody();
10601     DiagID = diag::warn_empty_while_body;
10602   } else
10603     return; // Neither `for' nor `while'.
10604
10605   // The body should be a null statement.
10606   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10607   if (!NBody)
10608     return;
10609
10610   // Skip expensive checks if diagnostic is disabled.
10611   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
10612     return;
10613
10614   // Do the usual checks.
10615   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10616     return;
10617
10618   // `for(...);' and `while(...);' are popular idioms, so in order to keep
10619   // noise level low, emit diagnostics only if for/while is followed by a
10620   // CompoundStmt, e.g.:
10621   //    for (int i = 0; i < n; i++);
10622   //    {
10623   //      a(i);
10624   //    }
10625   // or if for/while is followed by a statement with more indentation
10626   // than for/while itself:
10627   //    for (int i = 0; i < n; i++);
10628   //      a(i);
10629   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10630   if (!ProbableTypo) {
10631     bool BodyColInvalid;
10632     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10633                              PossibleBody->getLocStart(),
10634                              &BodyColInvalid);
10635     if (BodyColInvalid)
10636       return;
10637
10638     bool StmtColInvalid;
10639     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10640                              S->getLocStart(),
10641                              &StmtColInvalid);
10642     if (StmtColInvalid)
10643       return;
10644
10645     if (BodyCol > StmtCol)
10646       ProbableTypo = true;
10647   }
10648
10649   if (ProbableTypo) {
10650     Diag(NBody->getSemiLoc(), DiagID);
10651     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10652   }
10653 }
10654
10655 //===--- CHECK: Warn on self move with std::move. -------------------------===//
10656
10657 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10658 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10659                              SourceLocation OpLoc) {
10660   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10661     return;
10662
10663   if (!ActiveTemplateInstantiations.empty())
10664     return;
10665
10666   // Strip parens and casts away.
10667   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10668   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10669
10670   // Check for a call expression
10671   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10672   if (!CE || CE->getNumArgs() != 1)
10673     return;
10674
10675   // Check for a call to std::move
10676   const FunctionDecl *FD = CE->getDirectCallee();
10677   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10678       !FD->getIdentifier()->isStr("move"))
10679     return;
10680
10681   // Get argument from std::move
10682   RHSExpr = CE->getArg(0);
10683
10684   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10685   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10686
10687   // Two DeclRefExpr's, check that the decls are the same.
10688   if (LHSDeclRef && RHSDeclRef) {
10689     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10690       return;
10691     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10692         RHSDeclRef->getDecl()->getCanonicalDecl())
10693       return;
10694
10695     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10696                                         << LHSExpr->getSourceRange()
10697                                         << RHSExpr->getSourceRange();
10698     return;
10699   }
10700
10701   // Member variables require a different approach to check for self moves.
10702   // MemberExpr's are the same if every nested MemberExpr refers to the same
10703   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10704   // the base Expr's are CXXThisExpr's.
10705   const Expr *LHSBase = LHSExpr;
10706   const Expr *RHSBase = RHSExpr;
10707   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10708   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10709   if (!LHSME || !RHSME)
10710     return;
10711
10712   while (LHSME && RHSME) {
10713     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10714         RHSME->getMemberDecl()->getCanonicalDecl())
10715       return;
10716
10717     LHSBase = LHSME->getBase();
10718     RHSBase = RHSME->getBase();
10719     LHSME = dyn_cast<MemberExpr>(LHSBase);
10720     RHSME = dyn_cast<MemberExpr>(RHSBase);
10721   }
10722
10723   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10724   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10725   if (LHSDeclRef && RHSDeclRef) {
10726     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10727       return;
10728     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10729         RHSDeclRef->getDecl()->getCanonicalDecl())
10730       return;
10731
10732     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10733                                         << LHSExpr->getSourceRange()
10734                                         << RHSExpr->getSourceRange();
10735     return;
10736   }
10737
10738   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10739     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10740                                         << LHSExpr->getSourceRange()
10741                                         << RHSExpr->getSourceRange();
10742 }
10743
10744 //===--- Layout compatibility ----------------------------------------------//
10745
10746 namespace {
10747
10748 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10749
10750 /// \brief Check if two enumeration types are layout-compatible.
10751 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10752   // C++11 [dcl.enum] p8:
10753   // Two enumeration types are layout-compatible if they have the same
10754   // underlying type.
10755   return ED1->isComplete() && ED2->isComplete() &&
10756          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10757 }
10758
10759 /// \brief Check if two fields are layout-compatible.
10760 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10761   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10762     return false;
10763
10764   if (Field1->isBitField() != Field2->isBitField())
10765     return false;
10766
10767   if (Field1->isBitField()) {
10768     // Make sure that the bit-fields are the same length.
10769     unsigned Bits1 = Field1->getBitWidthValue(C);
10770     unsigned Bits2 = Field2->getBitWidthValue(C);
10771
10772     if (Bits1 != Bits2)
10773       return false;
10774   }
10775
10776   return true;
10777 }
10778
10779 /// \brief Check if two standard-layout structs are layout-compatible.
10780 /// (C++11 [class.mem] p17)
10781 bool isLayoutCompatibleStruct(ASTContext &C,
10782                               RecordDecl *RD1,
10783                               RecordDecl *RD2) {
10784   // If both records are C++ classes, check that base classes match.
10785   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10786     // If one of records is a CXXRecordDecl we are in C++ mode,
10787     // thus the other one is a CXXRecordDecl, too.
10788     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10789     // Check number of base classes.
10790     if (D1CXX->getNumBases() != D2CXX->getNumBases())
10791       return false;
10792
10793     // Check the base classes.
10794     for (CXXRecordDecl::base_class_const_iterator
10795                Base1 = D1CXX->bases_begin(),
10796            BaseEnd1 = D1CXX->bases_end(),
10797               Base2 = D2CXX->bases_begin();
10798          Base1 != BaseEnd1;
10799          ++Base1, ++Base2) {
10800       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10801         return false;
10802     }
10803   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10804     // If only RD2 is a C++ class, it should have zero base classes.
10805     if (D2CXX->getNumBases() > 0)
10806       return false;
10807   }
10808
10809   // Check the fields.
10810   RecordDecl::field_iterator Field2 = RD2->field_begin(),
10811                              Field2End = RD2->field_end(),
10812                              Field1 = RD1->field_begin(),
10813                              Field1End = RD1->field_end();
10814   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10815     if (!isLayoutCompatible(C, *Field1, *Field2))
10816       return false;
10817   }
10818   if (Field1 != Field1End || Field2 != Field2End)
10819     return false;
10820
10821   return true;
10822 }
10823
10824 /// \brief Check if two standard-layout unions are layout-compatible.
10825 /// (C++11 [class.mem] p18)
10826 bool isLayoutCompatibleUnion(ASTContext &C,
10827                              RecordDecl *RD1,
10828                              RecordDecl *RD2) {
10829   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10830   for (auto *Field2 : RD2->fields())
10831     UnmatchedFields.insert(Field2);
10832
10833   for (auto *Field1 : RD1->fields()) {
10834     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10835         I = UnmatchedFields.begin(),
10836         E = UnmatchedFields.end();
10837
10838     for ( ; I != E; ++I) {
10839       if (isLayoutCompatible(C, Field1, *I)) {
10840         bool Result = UnmatchedFields.erase(*I);
10841         (void) Result;
10842         assert(Result);
10843         break;
10844       }
10845     }
10846     if (I == E)
10847       return false;
10848   }
10849
10850   return UnmatchedFields.empty();
10851 }
10852
10853 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10854   if (RD1->isUnion() != RD2->isUnion())
10855     return false;
10856
10857   if (RD1->isUnion())
10858     return isLayoutCompatibleUnion(C, RD1, RD2);
10859   else
10860     return isLayoutCompatibleStruct(C, RD1, RD2);
10861 }
10862
10863 /// \brief Check if two types are layout-compatible in C++11 sense.
10864 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10865   if (T1.isNull() || T2.isNull())
10866     return false;
10867
10868   // C++11 [basic.types] p11:
10869   // If two types T1 and T2 are the same type, then T1 and T2 are
10870   // layout-compatible types.
10871   if (C.hasSameType(T1, T2))
10872     return true;
10873
10874   T1 = T1.getCanonicalType().getUnqualifiedType();
10875   T2 = T2.getCanonicalType().getUnqualifiedType();
10876
10877   const Type::TypeClass TC1 = T1->getTypeClass();
10878   const Type::TypeClass TC2 = T2->getTypeClass();
10879
10880   if (TC1 != TC2)
10881     return false;
10882
10883   if (TC1 == Type::Enum) {
10884     return isLayoutCompatible(C,
10885                               cast<EnumType>(T1)->getDecl(),
10886                               cast<EnumType>(T2)->getDecl());
10887   } else if (TC1 == Type::Record) {
10888     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10889       return false;
10890
10891     return isLayoutCompatible(C,
10892                               cast<RecordType>(T1)->getDecl(),
10893                               cast<RecordType>(T2)->getDecl());
10894   }
10895
10896   return false;
10897 }
10898 } // end anonymous namespace
10899
10900 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10901
10902 namespace {
10903 /// \brief Given a type tag expression find the type tag itself.
10904 ///
10905 /// \param TypeExpr Type tag expression, as it appears in user's code.
10906 ///
10907 /// \param VD Declaration of an identifier that appears in a type tag.
10908 ///
10909 /// \param MagicValue Type tag magic value.
10910 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10911                      const ValueDecl **VD, uint64_t *MagicValue) {
10912   while(true) {
10913     if (!TypeExpr)
10914       return false;
10915
10916     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10917
10918     switch (TypeExpr->getStmtClass()) {
10919     case Stmt::UnaryOperatorClass: {
10920       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10921       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10922         TypeExpr = UO->getSubExpr();
10923         continue;
10924       }
10925       return false;
10926     }
10927
10928     case Stmt::DeclRefExprClass: {
10929       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10930       *VD = DRE->getDecl();
10931       return true;
10932     }
10933
10934     case Stmt::IntegerLiteralClass: {
10935       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10936       llvm::APInt MagicValueAPInt = IL->getValue();
10937       if (MagicValueAPInt.getActiveBits() <= 64) {
10938         *MagicValue = MagicValueAPInt.getZExtValue();
10939         return true;
10940       } else
10941         return false;
10942     }
10943
10944     case Stmt::BinaryConditionalOperatorClass:
10945     case Stmt::ConditionalOperatorClass: {
10946       const AbstractConditionalOperator *ACO =
10947           cast<AbstractConditionalOperator>(TypeExpr);
10948       bool Result;
10949       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10950         if (Result)
10951           TypeExpr = ACO->getTrueExpr();
10952         else
10953           TypeExpr = ACO->getFalseExpr();
10954         continue;
10955       }
10956       return false;
10957     }
10958
10959     case Stmt::BinaryOperatorClass: {
10960       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10961       if (BO->getOpcode() == BO_Comma) {
10962         TypeExpr = BO->getRHS();
10963         continue;
10964       }
10965       return false;
10966     }
10967
10968     default:
10969       return false;
10970     }
10971   }
10972 }
10973
10974 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
10975 ///
10976 /// \param TypeExpr Expression that specifies a type tag.
10977 ///
10978 /// \param MagicValues Registered magic values.
10979 ///
10980 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10981 ///        kind.
10982 ///
10983 /// \param TypeInfo Information about the corresponding C type.
10984 ///
10985 /// \returns true if the corresponding C type was found.
10986 bool GetMatchingCType(
10987         const IdentifierInfo *ArgumentKind,
10988         const Expr *TypeExpr, const ASTContext &Ctx,
10989         const llvm::DenseMap<Sema::TypeTagMagicValue,
10990                              Sema::TypeTagData> *MagicValues,
10991         bool &FoundWrongKind,
10992         Sema::TypeTagData &TypeInfo) {
10993   FoundWrongKind = false;
10994
10995   // Variable declaration that has type_tag_for_datatype attribute.
10996   const ValueDecl *VD = nullptr;
10997
10998   uint64_t MagicValue;
10999
11000   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11001     return false;
11002
11003   if (VD) {
11004     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11005       if (I->getArgumentKind() != ArgumentKind) {
11006         FoundWrongKind = true;
11007         return false;
11008       }
11009       TypeInfo.Type = I->getMatchingCType();
11010       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11011       TypeInfo.MustBeNull = I->getMustBeNull();
11012       return true;
11013     }
11014     return false;
11015   }
11016
11017   if (!MagicValues)
11018     return false;
11019
11020   llvm::DenseMap<Sema::TypeTagMagicValue,
11021                  Sema::TypeTagData>::const_iterator I =
11022       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11023   if (I == MagicValues->end())
11024     return false;
11025
11026   TypeInfo = I->second;
11027   return true;
11028 }
11029 } // end anonymous namespace
11030
11031 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11032                                       uint64_t MagicValue, QualType Type,
11033                                       bool LayoutCompatible,
11034                                       bool MustBeNull) {
11035   if (!TypeTagForDatatypeMagicValues)
11036     TypeTagForDatatypeMagicValues.reset(
11037         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11038
11039   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11040   (*TypeTagForDatatypeMagicValues)[Magic] =
11041       TypeTagData(Type, LayoutCompatible, MustBeNull);
11042 }
11043
11044 namespace {
11045 bool IsSameCharType(QualType T1, QualType T2) {
11046   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11047   if (!BT1)
11048     return false;
11049
11050   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11051   if (!BT2)
11052     return false;
11053
11054   BuiltinType::Kind T1Kind = BT1->getKind();
11055   BuiltinType::Kind T2Kind = BT2->getKind();
11056
11057   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11058          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11059          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11060          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11061 }
11062 } // end anonymous namespace
11063
11064 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11065                                     const Expr * const *ExprArgs) {
11066   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11067   bool IsPointerAttr = Attr->getIsPointer();
11068
11069   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11070   bool FoundWrongKind;
11071   TypeTagData TypeInfo;
11072   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11073                         TypeTagForDatatypeMagicValues.get(),
11074                         FoundWrongKind, TypeInfo)) {
11075     if (FoundWrongKind)
11076       Diag(TypeTagExpr->getExprLoc(),
11077            diag::warn_type_tag_for_datatype_wrong_kind)
11078         << TypeTagExpr->getSourceRange();
11079     return;
11080   }
11081
11082   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11083   if (IsPointerAttr) {
11084     // Skip implicit cast of pointer to `void *' (as a function argument).
11085     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11086       if (ICE->getType()->isVoidPointerType() &&
11087           ICE->getCastKind() == CK_BitCast)
11088         ArgumentExpr = ICE->getSubExpr();
11089   }
11090   QualType ArgumentType = ArgumentExpr->getType();
11091
11092   // Passing a `void*' pointer shouldn't trigger a warning.
11093   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11094     return;
11095
11096   if (TypeInfo.MustBeNull) {
11097     // Type tag with matching void type requires a null pointer.
11098     if (!ArgumentExpr->isNullPointerConstant(Context,
11099                                              Expr::NPC_ValueDependentIsNotNull)) {
11100       Diag(ArgumentExpr->getExprLoc(),
11101            diag::warn_type_safety_null_pointer_required)
11102           << ArgumentKind->getName()
11103           << ArgumentExpr->getSourceRange()
11104           << TypeTagExpr->getSourceRange();
11105     }
11106     return;
11107   }
11108
11109   QualType RequiredType = TypeInfo.Type;
11110   if (IsPointerAttr)
11111     RequiredType = Context.getPointerType(RequiredType);
11112
11113   bool mismatch = false;
11114   if (!TypeInfo.LayoutCompatible) {
11115     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11116
11117     // C++11 [basic.fundamental] p1:
11118     // Plain char, signed char, and unsigned char are three distinct types.
11119     //
11120     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11121     // char' depending on the current char signedness mode.
11122     if (mismatch)
11123       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11124                                            RequiredType->getPointeeType())) ||
11125           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11126         mismatch = false;
11127   } else
11128     if (IsPointerAttr)
11129       mismatch = !isLayoutCompatible(Context,
11130                                      ArgumentType->getPointeeType(),
11131                                      RequiredType->getPointeeType());
11132     else
11133       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11134
11135   if (mismatch)
11136     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11137         << ArgumentType << ArgumentKind
11138         << TypeInfo.LayoutCompatible << RequiredType
11139         << ArgumentExpr->getSourceRange()
11140         << TypeTagExpr->getSourceRange();
11141 }