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