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