]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp
Update clang to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaChecking.cpp
1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43
44 using namespace clang;
45 using namespace sema;
46
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67     
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96
97   TheCall->setType(Ty);
98   return false;
99 }
100
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146
147   return false;
148 }
149
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151                                   CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160   llvm::APSInt Size, DstSize;
161
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166
167   if (Size.ule(DstSize))
168     return;
169
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237
238   return false;
239 }
240
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (!SemaRef.ActiveTemplateInstantiations.empty())
248     return false;
249
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259
260   return false;
261 }
262
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298
299   return IllegalParams;
300 }
301
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317
318 /// Diagnose integer type and any valid implicit convertion to it.
319 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320                                       const QualType &IntType);
321
322 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
323                                             unsigned Start, unsigned End) {
324   bool IllegalParams = false;
325   for (unsigned I = Start; I <= End; ++I)
326     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327                                               S.Context.getSizeType());
328   return IllegalParams;
329 }
330
331 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332 /// 'local void*' parameter of passed block.
333 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
334                                            Expr *BlockArg,
335                                            unsigned NumNonVarArgs) {
336   const BlockPointerType *BPT =
337       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338   unsigned NumBlockParams =
339       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340   unsigned TotalNumArgs = TheCall->getNumArgs();
341
342   // For each argument passed to the block, a corresponding uint needs to
343   // be passed to describe the size of the local memory.
344   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345     S.Diag(TheCall->getLocStart(),
346            diag::err_opencl_enqueue_kernel_local_size_args);
347     return true;
348   }
349
350   // Check that the sizes of the local memory are specified by integers.
351   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
352                                          TotalNumArgs - 1);
353 }
354
355 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356 /// overload formats specified in Table 6.13.17.1.
357 /// int enqueue_kernel(queue_t queue,
358 ///                    kernel_enqueue_flags_t flags,
359 ///                    const ndrange_t ndrange,
360 ///                    void (^block)(void))
361 /// int enqueue_kernel(queue_t queue,
362 ///                    kernel_enqueue_flags_t flags,
363 ///                    const ndrange_t ndrange,
364 ///                    uint num_events_in_wait_list,
365 ///                    clk_event_t *event_wait_list,
366 ///                    clk_event_t *event_ret,
367 ///                    void (^block)(void))
368 /// int enqueue_kernel(queue_t queue,
369 ///                    kernel_enqueue_flags_t flags,
370 ///                    const ndrange_t ndrange,
371 ///                    void (^block)(local void*, ...),
372 ///                    uint size0, ...)
373 /// int enqueue_kernel(queue_t queue,
374 ///                    kernel_enqueue_flags_t flags,
375 ///                    const ndrange_t ndrange,
376 ///                    uint num_events_in_wait_list,
377 ///                    clk_event_t *event_wait_list,
378 ///                    clk_event_t *event_ret,
379 ///                    void (^block)(local void*, ...),
380 ///                    uint size0, ...)
381 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382   unsigned NumArgs = TheCall->getNumArgs();
383
384   if (NumArgs < 4) {
385     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
386     return true;
387   }
388
389   Expr *Arg0 = TheCall->getArg(0);
390   Expr *Arg1 = TheCall->getArg(1);
391   Expr *Arg2 = TheCall->getArg(2);
392   Expr *Arg3 = TheCall->getArg(3);
393
394   // First argument always needs to be a queue_t type.
395   if (!Arg0->getType()->isQueueT()) {
396     S.Diag(TheCall->getArg(0)->getLocStart(),
397            diag::err_opencl_enqueue_kernel_expected_type)
398         << S.Context.OCLQueueTy;
399     return true;
400   }
401
402   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403   if (!Arg1->getType()->isIntegerType()) {
404     S.Diag(TheCall->getArg(1)->getLocStart(),
405            diag::err_opencl_enqueue_kernel_expected_type)
406         << "'kernel_enqueue_flags_t' (i.e. uint)";
407     return true;
408   }
409
410   // Third argument is always an ndrange_t type.
411   if (!Arg2->getType()->isNDRangeT()) {
412     S.Diag(TheCall->getArg(2)->getLocStart(),
413            diag::err_opencl_enqueue_kernel_expected_type)
414         << S.Context.OCLNDRangeTy;
415     return true;
416   }
417
418   // With four arguments, there is only one form that the function could be
419   // called in: no events and no variable arguments.
420   if (NumArgs == 4) {
421     // check that the last argument is the right block type.
422     if (!isBlockPointer(Arg3)) {
423       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424           << "block";
425       return true;
426     }
427     // we have a block type, check the prototype
428     const BlockPointerType *BPT =
429         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431       S.Diag(Arg3->getLocStart(),
432              diag::err_opencl_enqueue_kernel_blocks_no_args);
433       return true;
434     }
435     return false;
436   }
437   // we can have block + varargs.
438   if (isBlockPointer(Arg3))
439     return (checkOpenCLBlockArgs(S, Arg3) ||
440             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441   // last two cases with either exactly 7 args or 7 args and varargs.
442   if (NumArgs >= 7) {
443     // check common block argument.
444     Expr *Arg6 = TheCall->getArg(6);
445     if (!isBlockPointer(Arg6)) {
446       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447           << "block";
448       return true;
449     }
450     if (checkOpenCLBlockArgs(S, Arg6))
451       return true;
452
453     // Forth argument has to be any integer type.
454     if (!Arg3->getType()->isIntegerType()) {
455       S.Diag(TheCall->getArg(3)->getLocStart(),
456              diag::err_opencl_enqueue_kernel_expected_type)
457           << "integer";
458       return true;
459     }
460     // check remaining common arguments.
461     Expr *Arg4 = TheCall->getArg(4);
462     Expr *Arg5 = TheCall->getArg(5);
463
464     // Fifth argument is always passed as a pointer to clk_event_t.
465     if (!Arg4->isNullPointerConstant(S.Context,
466                                      Expr::NPC_ValueDependentIsNotNull) &&
467         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
468       S.Diag(TheCall->getArg(4)->getLocStart(),
469              diag::err_opencl_enqueue_kernel_expected_type)
470           << S.Context.getPointerType(S.Context.OCLClkEventTy);
471       return true;
472     }
473
474     // Sixth argument is always passed as a pointer to clk_event_t.
475     if (!Arg5->isNullPointerConstant(S.Context,
476                                      Expr::NPC_ValueDependentIsNotNull) &&
477         !(Arg5->getType()->isPointerType() &&
478           Arg5->getType()->getPointeeType()->isClkEventT())) {
479       S.Diag(TheCall->getArg(5)->getLocStart(),
480              diag::err_opencl_enqueue_kernel_expected_type)
481           << S.Context.getPointerType(S.Context.OCLClkEventTy);
482       return true;
483     }
484
485     if (NumArgs == 7)
486       return false;
487
488     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489   }
490
491   // None of the specific case has been detected, give generic error
492   S.Diag(TheCall->getLocStart(),
493          diag::err_opencl_enqueue_kernel_incorrect_args);
494   return true;
495 }
496
497 /// Returns OpenCL access qual.
498 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
499     return D->getAttr<OpenCLAccessAttr>();
500 }
501
502 /// Returns true if pipe element type is different from the pointer.
503 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504   const Expr *Arg0 = Call->getArg(0);
505   // First argument type should always be pipe.
506   if (!Arg0->getType()->isPipeType()) {
507     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
508         << Call->getDirectCallee() << Arg0->getSourceRange();
509     return true;
510   }
511   OpenCLAccessAttr *AccessQual =
512       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513   // Validates the access qualifier is compatible with the call.
514   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515   // read_only and write_only, and assumed to be read_only if no qualifier is
516   // specified.
517   switch (Call->getDirectCallee()->getBuiltinID()) {
518   case Builtin::BIread_pipe:
519   case Builtin::BIreserve_read_pipe:
520   case Builtin::BIcommit_read_pipe:
521   case Builtin::BIwork_group_reserve_read_pipe:
522   case Builtin::BIsub_group_reserve_read_pipe:
523   case Builtin::BIwork_group_commit_read_pipe:
524   case Builtin::BIsub_group_commit_read_pipe:
525     if (!(!AccessQual || AccessQual->isReadOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "read_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   case Builtin::BIwrite_pipe:
533   case Builtin::BIreserve_write_pipe:
534   case Builtin::BIcommit_write_pipe:
535   case Builtin::BIwork_group_reserve_write_pipe:
536   case Builtin::BIsub_group_reserve_write_pipe:
537   case Builtin::BIwork_group_commit_write_pipe:
538   case Builtin::BIsub_group_commit_write_pipe:
539     if (!(AccessQual && AccessQual->isWriteOnly())) {
540       S.Diag(Arg0->getLocStart(),
541              diag::err_opencl_builtin_pipe_invalid_access_modifier)
542           << "write_only" << Arg0->getSourceRange();
543       return true;
544     }
545     break;
546   default:
547     break;
548   }
549   return false;
550 }
551
552 /// Returns true if pipe element type is different from the pointer.
553 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554   const Expr *Arg0 = Call->getArg(0);
555   const Expr *ArgIdx = Call->getArg(Idx);
556   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
557   const QualType EltTy = PipeTy->getElementType();
558   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
559   // The Idx argument should be a pointer and the type of the pointer and
560   // the type of pipe element should also be the same.
561   if (!ArgTy ||
562       !S.Context.hasSameType(
563           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
564     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
565         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
566         << ArgIdx->getType() << ArgIdx->getSourceRange();
567     return true;
568   }
569   return false;
570 }
571
572 // \brief Performs semantic analysis for the read/write_pipe call.
573 // \param S Reference to the semantic analyzer.
574 // \param Call A pointer to the builtin call.
575 // \return True if a semantic error has been found, false otherwise.
576 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
577   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578   // functions have two forms.
579   switch (Call->getNumArgs()) {
580   case 2: {
581     if (checkOpenCLPipeArg(S, Call))
582       return true;
583     // The call with 2 arguments should be
584     // read/write_pipe(pipe T, T*).
585     // Check packet type T.
586     if (checkOpenCLPipePacketType(S, Call, 1))
587       return true;
588   } break;
589
590   case 4: {
591     if (checkOpenCLPipeArg(S, Call))
592       return true;
593     // The call with 4 arguments should be
594     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595     // Check reserve_id_t.
596     if (!Call->getArg(1)->getType()->isReserveIDT()) {
597       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
598           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
599           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
600       return true;
601     }
602
603     // Check the index.
604     const Expr *Arg2 = Call->getArg(2);
605     if (!Arg2->getType()->isIntegerType() &&
606         !Arg2->getType()->isUnsignedIntegerType()) {
607       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
608           << Call->getDirectCallee() << S.Context.UnsignedIntTy
609           << Arg2->getType() << Arg2->getSourceRange();
610       return true;
611     }
612
613     // Check packet type T.
614     if (checkOpenCLPipePacketType(S, Call, 3))
615       return true;
616   } break;
617   default:
618     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
619         << Call->getDirectCallee() << Call->getSourceRange();
620     return true;
621   }
622
623   return false;
624 }
625
626 // \brief Performs a semantic analysis on the {work_group_/sub_group_
627 //        /_}reserve_{read/write}_pipe
628 // \param S Reference to the semantic analyzer.
629 // \param Call The call to the builtin function to be analyzed.
630 // \return True if a semantic error was found, false otherwise.
631 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632   if (checkArgCount(S, Call, 2))
633     return true;
634
635   if (checkOpenCLPipeArg(S, Call))
636     return true;
637
638   // Check the reserve size.
639   if (!Call->getArg(1)->getType()->isIntegerType() &&
640       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
642         << Call->getDirectCallee() << S.Context.UnsignedIntTy
643         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
644     return true;
645   }
646
647   return false;
648 }
649
650 // \brief Performs a semantic analysis on {work_group_/sub_group_
651 //        /_}commit_{read/write}_pipe
652 // \param S Reference to the semantic analyzer.
653 // \param Call The call to the builtin function to be analyzed.
654 // \return True if a semantic error was found, false otherwise.
655 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656   if (checkArgCount(S, Call, 2))
657     return true;
658
659   if (checkOpenCLPipeArg(S, Call))
660     return true;
661
662   // Check reserve_id_t.
663   if (!Call->getArg(1)->getType()->isReserveIDT()) {
664     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
665         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
666         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
667     return true;
668   }
669
670   return false;
671 }
672
673 // \brief Performs a semantic analysis on the call to built-in Pipe
674 //        Query Functions.
675 // \param S Reference to the semantic analyzer.
676 // \param Call The call to the builtin function to be analyzed.
677 // \return True if a semantic error was found, false otherwise.
678 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679   if (checkArgCount(S, Call, 1))
680     return true;
681
682   if (!Call->getArg(0)->getType()->isPipeType()) {
683     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
684         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
685     return true;
686   }
687
688   return false;
689 }
690 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
691 // \brief Performs semantic analysis for the to_global/local/private call.
692 // \param S Reference to the semantic analyzer.
693 // \param BuiltinID ID of the builtin function.
694 // \param Call A pointer to the builtin call.
695 // \return True if a semantic error has been found, false otherwise.
696 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697                                     CallExpr *Call) {
698   if (Call->getNumArgs() != 1) {
699     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700         << Call->getDirectCallee() << Call->getSourceRange();
701     return true;
702   }
703
704   auto RT = Call->getArg(0)->getType();
705   if (!RT->isPointerType() || RT->getPointeeType()
706       .getAddressSpace() == LangAS::opencl_constant) {
707     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709     return true;
710   }
711
712   RT = RT->getPointeeType();
713   auto Qual = RT.getQualifiers();
714   switch (BuiltinID) {
715   case Builtin::BIto_global:
716     Qual.setAddressSpace(LangAS::opencl_global);
717     break;
718   case Builtin::BIto_local:
719     Qual.setAddressSpace(LangAS::opencl_local);
720     break;
721   default:
722     Qual.removeAddressSpace();
723   }
724   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725       RT.getUnqualifiedType(), Qual)));
726
727   return false;
728 }
729
730 ExprResult
731 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732                                CallExpr *TheCall) {
733   ExprResult TheCallResult(TheCall);
734
735   // Find out if any arguments are required to be integer constant expressions.
736   unsigned ICEArguments = 0;
737   ASTContext::GetBuiltinTypeError Error;
738   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739   if (Error != ASTContext::GE_None)
740     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
741   
742   // If any arguments are required to be ICE's, check and diagnose.
743   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744     // Skip arguments not required to be ICE's.
745     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746     
747     llvm::APSInt Result;
748     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749       return true;
750     ICEArguments &= ~(1 << ArgNo);
751   }
752   
753   switch (BuiltinID) {
754   case Builtin::BI__builtin___CFStringMakeConstantString:
755     assert(TheCall->getNumArgs() == 1 &&
756            "Wrong # arguments to builtin CFStringMakeConstantString");
757     if (CheckObjCString(TheCall->getArg(0)))
758       return ExprError();
759     break;
760   case Builtin::BI__builtin_stdarg_start:
761   case Builtin::BI__builtin_va_start:
762     if (SemaBuiltinVAStart(TheCall))
763       return ExprError();
764     break;
765   case Builtin::BI__va_start: {
766     switch (Context.getTargetInfo().getTriple().getArch()) {
767     case llvm::Triple::arm:
768     case llvm::Triple::thumb:
769       if (SemaBuiltinVAStartARM(TheCall))
770         return ExprError();
771       break;
772     default:
773       if (SemaBuiltinVAStart(TheCall))
774         return ExprError();
775       break;
776     }
777     break;
778   }
779   case Builtin::BI__builtin_isgreater:
780   case Builtin::BI__builtin_isgreaterequal:
781   case Builtin::BI__builtin_isless:
782   case Builtin::BI__builtin_islessequal:
783   case Builtin::BI__builtin_islessgreater:
784   case Builtin::BI__builtin_isunordered:
785     if (SemaBuiltinUnorderedCompare(TheCall))
786       return ExprError();
787     break;
788   case Builtin::BI__builtin_fpclassify:
789     if (SemaBuiltinFPClassification(TheCall, 6))
790       return ExprError();
791     break;
792   case Builtin::BI__builtin_isfinite:
793   case Builtin::BI__builtin_isinf:
794   case Builtin::BI__builtin_isinf_sign:
795   case Builtin::BI__builtin_isnan:
796   case Builtin::BI__builtin_isnormal:
797     if (SemaBuiltinFPClassification(TheCall, 1))
798       return ExprError();
799     break;
800   case Builtin::BI__builtin_shufflevector:
801     return SemaBuiltinShuffleVector(TheCall);
802     // TheCall will be freed by the smart pointer here, but that's fine, since
803     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
804   case Builtin::BI__builtin_prefetch:
805     if (SemaBuiltinPrefetch(TheCall))
806       return ExprError();
807     break;
808   case Builtin::BI__builtin_alloca_with_align:
809     if (SemaBuiltinAllocaWithAlign(TheCall))
810       return ExprError();
811     break;
812   case Builtin::BI__assume:
813   case Builtin::BI__builtin_assume:
814     if (SemaBuiltinAssume(TheCall))
815       return ExprError();
816     break;
817   case Builtin::BI__builtin_assume_aligned:
818     if (SemaBuiltinAssumeAligned(TheCall))
819       return ExprError();
820     break;
821   case Builtin::BI__builtin_object_size:
822     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
823       return ExprError();
824     break;
825   case Builtin::BI__builtin_longjmp:
826     if (SemaBuiltinLongjmp(TheCall))
827       return ExprError();
828     break;
829   case Builtin::BI__builtin_setjmp:
830     if (SemaBuiltinSetjmp(TheCall))
831       return ExprError();
832     break;
833   case Builtin::BI_setjmp:
834   case Builtin::BI_setjmpex:
835     if (checkArgCount(*this, TheCall, 1))
836       return true;
837     break;
838
839   case Builtin::BI__builtin_classify_type:
840     if (checkArgCount(*this, TheCall, 1)) return true;
841     TheCall->setType(Context.IntTy);
842     break;
843   case Builtin::BI__builtin_constant_p:
844     if (checkArgCount(*this, TheCall, 1)) return true;
845     TheCall->setType(Context.IntTy);
846     break;
847   case Builtin::BI__sync_fetch_and_add:
848   case Builtin::BI__sync_fetch_and_add_1:
849   case Builtin::BI__sync_fetch_and_add_2:
850   case Builtin::BI__sync_fetch_and_add_4:
851   case Builtin::BI__sync_fetch_and_add_8:
852   case Builtin::BI__sync_fetch_and_add_16:
853   case Builtin::BI__sync_fetch_and_sub:
854   case Builtin::BI__sync_fetch_and_sub_1:
855   case Builtin::BI__sync_fetch_and_sub_2:
856   case Builtin::BI__sync_fetch_and_sub_4:
857   case Builtin::BI__sync_fetch_and_sub_8:
858   case Builtin::BI__sync_fetch_and_sub_16:
859   case Builtin::BI__sync_fetch_and_or:
860   case Builtin::BI__sync_fetch_and_or_1:
861   case Builtin::BI__sync_fetch_and_or_2:
862   case Builtin::BI__sync_fetch_and_or_4:
863   case Builtin::BI__sync_fetch_and_or_8:
864   case Builtin::BI__sync_fetch_and_or_16:
865   case Builtin::BI__sync_fetch_and_and:
866   case Builtin::BI__sync_fetch_and_and_1:
867   case Builtin::BI__sync_fetch_and_and_2:
868   case Builtin::BI__sync_fetch_and_and_4:
869   case Builtin::BI__sync_fetch_and_and_8:
870   case Builtin::BI__sync_fetch_and_and_16:
871   case Builtin::BI__sync_fetch_and_xor:
872   case Builtin::BI__sync_fetch_and_xor_1:
873   case Builtin::BI__sync_fetch_and_xor_2:
874   case Builtin::BI__sync_fetch_and_xor_4:
875   case Builtin::BI__sync_fetch_and_xor_8:
876   case Builtin::BI__sync_fetch_and_xor_16:
877   case Builtin::BI__sync_fetch_and_nand:
878   case Builtin::BI__sync_fetch_and_nand_1:
879   case Builtin::BI__sync_fetch_and_nand_2:
880   case Builtin::BI__sync_fetch_and_nand_4:
881   case Builtin::BI__sync_fetch_and_nand_8:
882   case Builtin::BI__sync_fetch_and_nand_16:
883   case Builtin::BI__sync_add_and_fetch:
884   case Builtin::BI__sync_add_and_fetch_1:
885   case Builtin::BI__sync_add_and_fetch_2:
886   case Builtin::BI__sync_add_and_fetch_4:
887   case Builtin::BI__sync_add_and_fetch_8:
888   case Builtin::BI__sync_add_and_fetch_16:
889   case Builtin::BI__sync_sub_and_fetch:
890   case Builtin::BI__sync_sub_and_fetch_1:
891   case Builtin::BI__sync_sub_and_fetch_2:
892   case Builtin::BI__sync_sub_and_fetch_4:
893   case Builtin::BI__sync_sub_and_fetch_8:
894   case Builtin::BI__sync_sub_and_fetch_16:
895   case Builtin::BI__sync_and_and_fetch:
896   case Builtin::BI__sync_and_and_fetch_1:
897   case Builtin::BI__sync_and_and_fetch_2:
898   case Builtin::BI__sync_and_and_fetch_4:
899   case Builtin::BI__sync_and_and_fetch_8:
900   case Builtin::BI__sync_and_and_fetch_16:
901   case Builtin::BI__sync_or_and_fetch:
902   case Builtin::BI__sync_or_and_fetch_1:
903   case Builtin::BI__sync_or_and_fetch_2:
904   case Builtin::BI__sync_or_and_fetch_4:
905   case Builtin::BI__sync_or_and_fetch_8:
906   case Builtin::BI__sync_or_and_fetch_16:
907   case Builtin::BI__sync_xor_and_fetch:
908   case Builtin::BI__sync_xor_and_fetch_1:
909   case Builtin::BI__sync_xor_and_fetch_2:
910   case Builtin::BI__sync_xor_and_fetch_4:
911   case Builtin::BI__sync_xor_and_fetch_8:
912   case Builtin::BI__sync_xor_and_fetch_16:
913   case Builtin::BI__sync_nand_and_fetch:
914   case Builtin::BI__sync_nand_and_fetch_1:
915   case Builtin::BI__sync_nand_and_fetch_2:
916   case Builtin::BI__sync_nand_and_fetch_4:
917   case Builtin::BI__sync_nand_and_fetch_8:
918   case Builtin::BI__sync_nand_and_fetch_16:
919   case Builtin::BI__sync_val_compare_and_swap:
920   case Builtin::BI__sync_val_compare_and_swap_1:
921   case Builtin::BI__sync_val_compare_and_swap_2:
922   case Builtin::BI__sync_val_compare_and_swap_4:
923   case Builtin::BI__sync_val_compare_and_swap_8:
924   case Builtin::BI__sync_val_compare_and_swap_16:
925   case Builtin::BI__sync_bool_compare_and_swap:
926   case Builtin::BI__sync_bool_compare_and_swap_1:
927   case Builtin::BI__sync_bool_compare_and_swap_2:
928   case Builtin::BI__sync_bool_compare_and_swap_4:
929   case Builtin::BI__sync_bool_compare_and_swap_8:
930   case Builtin::BI__sync_bool_compare_and_swap_16:
931   case Builtin::BI__sync_lock_test_and_set:
932   case Builtin::BI__sync_lock_test_and_set_1:
933   case Builtin::BI__sync_lock_test_and_set_2:
934   case Builtin::BI__sync_lock_test_and_set_4:
935   case Builtin::BI__sync_lock_test_and_set_8:
936   case Builtin::BI__sync_lock_test_and_set_16:
937   case Builtin::BI__sync_lock_release:
938   case Builtin::BI__sync_lock_release_1:
939   case Builtin::BI__sync_lock_release_2:
940   case Builtin::BI__sync_lock_release_4:
941   case Builtin::BI__sync_lock_release_8:
942   case Builtin::BI__sync_lock_release_16:
943   case Builtin::BI__sync_swap:
944   case Builtin::BI__sync_swap_1:
945   case Builtin::BI__sync_swap_2:
946   case Builtin::BI__sync_swap_4:
947   case Builtin::BI__sync_swap_8:
948   case Builtin::BI__sync_swap_16:
949     return SemaBuiltinAtomicOverloaded(TheCallResult);
950   case Builtin::BI__builtin_nontemporal_load:
951   case Builtin::BI__builtin_nontemporal_store:
952     return SemaBuiltinNontemporalOverloaded(TheCallResult);
953 #define BUILTIN(ID, TYPE, ATTRS)
954 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955   case Builtin::BI##ID: \
956     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
957 #include "clang/Basic/Builtins.def"
958   case Builtin::BI__builtin_annotation:
959     if (SemaBuiltinAnnotation(*this, TheCall))
960       return ExprError();
961     break;
962   case Builtin::BI__builtin_addressof:
963     if (SemaBuiltinAddressof(*this, TheCall))
964       return ExprError();
965     break;
966   case Builtin::BI__builtin_add_overflow:
967   case Builtin::BI__builtin_sub_overflow:
968   case Builtin::BI__builtin_mul_overflow:
969     if (SemaBuiltinOverflow(*this, TheCall))
970       return ExprError();
971     break;
972   case Builtin::BI__builtin_operator_new:
973   case Builtin::BI__builtin_operator_delete:
974     if (!getLangOpts().CPlusPlus) {
975       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976         << (BuiltinID == Builtin::BI__builtin_operator_new
977                 ? "__builtin_operator_new"
978                 : "__builtin_operator_delete")
979         << "C++";
980       return ExprError();
981     }
982     // CodeGen assumes it can find the global new and delete to call,
983     // so ensure that they are declared.
984     DeclareGlobalNewDelete();
985     break;
986
987   // check secure string manipulation functions where overflows
988   // are detectable at compile time
989   case Builtin::BI__builtin___memcpy_chk:
990   case Builtin::BI__builtin___memmove_chk:
991   case Builtin::BI__builtin___memset_chk:
992   case Builtin::BI__builtin___strlcat_chk:
993   case Builtin::BI__builtin___strlcpy_chk:
994   case Builtin::BI__builtin___strncat_chk:
995   case Builtin::BI__builtin___strncpy_chk:
996   case Builtin::BI__builtin___stpncpy_chk:
997     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998     break;
999   case Builtin::BI__builtin___memccpy_chk:
1000     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001     break;
1002   case Builtin::BI__builtin___snprintf_chk:
1003   case Builtin::BI__builtin___vsnprintf_chk:
1004     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005     break;
1006   case Builtin::BI__builtin_call_with_static_chain:
1007     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008       return ExprError();
1009     break;
1010   case Builtin::BI__exception_code:
1011   case Builtin::BI_exception_code:
1012     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013                                  diag::err_seh___except_block))
1014       return ExprError();
1015     break;
1016   case Builtin::BI__exception_info:
1017   case Builtin::BI_exception_info:
1018     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019                                  diag::err_seh___except_filter))
1020       return ExprError();
1021     break;
1022   case Builtin::BI__GetExceptionInfo:
1023     if (checkArgCount(*this, TheCall, 1))
1024       return ExprError();
1025
1026     if (CheckCXXThrowOperand(
1027             TheCall->getLocStart(),
1028             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029             TheCall))
1030       return ExprError();
1031
1032     TheCall->setType(Context.VoidPtrTy);
1033     break;
1034   // OpenCL v2.0, s6.13.16 - Pipe functions
1035   case Builtin::BIread_pipe:
1036   case Builtin::BIwrite_pipe:
1037     // Since those two functions are declared with var args, we need a semantic
1038     // check for the argument.
1039     if (SemaBuiltinRWPipe(*this, TheCall))
1040       return ExprError();
1041     TheCall->setType(Context.IntTy);
1042     break;
1043   case Builtin::BIreserve_read_pipe:
1044   case Builtin::BIreserve_write_pipe:
1045   case Builtin::BIwork_group_reserve_read_pipe:
1046   case Builtin::BIwork_group_reserve_write_pipe:
1047   case Builtin::BIsub_group_reserve_read_pipe:
1048   case Builtin::BIsub_group_reserve_write_pipe:
1049     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050       return ExprError();
1051     // Since return type of reserve_read/write_pipe built-in function is
1052     // reserve_id_t, which is not defined in the builtin def file , we used int
1053     // as return type and need to override the return type of these functions.
1054     TheCall->setType(Context.OCLReserveIDTy);
1055     break;
1056   case Builtin::BIcommit_read_pipe:
1057   case Builtin::BIcommit_write_pipe:
1058   case Builtin::BIwork_group_commit_read_pipe:
1059   case Builtin::BIwork_group_commit_write_pipe:
1060   case Builtin::BIsub_group_commit_read_pipe:
1061   case Builtin::BIsub_group_commit_write_pipe:
1062     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063       return ExprError();
1064     break;
1065   case Builtin::BIget_pipe_num_packets:
1066   case Builtin::BIget_pipe_max_packets:
1067     if (SemaBuiltinPipePackets(*this, TheCall))
1068       return ExprError();
1069     TheCall->setType(Context.UnsignedIntTy);
1070     break;
1071   case Builtin::BIto_global:
1072   case Builtin::BIto_local:
1073   case Builtin::BIto_private:
1074     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075       return ExprError();
1076     break;
1077   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078   case Builtin::BIenqueue_kernel:
1079     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080       return ExprError();
1081     break;
1082   case Builtin::BIget_kernel_work_group_size:
1083   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__builtin_os_log_format:
1088   case Builtin::BI__builtin_os_log_format_buffer_size:
1089     if (SemaBuiltinOSLogFormat(TheCall)) {
1090       return ExprError();
1091     }
1092     break;
1093   }
1094
1095   // Since the target specific builtins for each arch overlap, only check those
1096   // of the arch we are compiling for.
1097   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1098     switch (Context.getTargetInfo().getTriple().getArch()) {
1099       case llvm::Triple::arm:
1100       case llvm::Triple::armeb:
1101       case llvm::Triple::thumb:
1102       case llvm::Triple::thumbeb:
1103         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104           return ExprError();
1105         break;
1106       case llvm::Triple::aarch64:
1107       case llvm::Triple::aarch64_be:
1108         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1109           return ExprError();
1110         break;
1111       case llvm::Triple::mips:
1112       case llvm::Triple::mipsel:
1113       case llvm::Triple::mips64:
1114       case llvm::Triple::mips64el:
1115         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116           return ExprError();
1117         break;
1118       case llvm::Triple::systemz:
1119         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120           return ExprError();
1121         break;
1122       case llvm::Triple::x86:
1123       case llvm::Triple::x86_64:
1124         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125           return ExprError();
1126         break;
1127       case llvm::Triple::ppc:
1128       case llvm::Triple::ppc64:
1129       case llvm::Triple::ppc64le:
1130         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131           return ExprError();
1132         break;
1133       default:
1134         break;
1135     }
1136   }
1137
1138   return TheCallResult;
1139 }
1140
1141 // Get the valid immediate range for the specified NEON type code.
1142 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1143   NeonTypeFlags Type(t);
1144   int IsQuad = ForceQuad ? true : Type.isQuad();
1145   switch (Type.getEltType()) {
1146   case NeonTypeFlags::Int8:
1147   case NeonTypeFlags::Poly8:
1148     return shift ? 7 : (8 << IsQuad) - 1;
1149   case NeonTypeFlags::Int16:
1150   case NeonTypeFlags::Poly16:
1151     return shift ? 15 : (4 << IsQuad) - 1;
1152   case NeonTypeFlags::Int32:
1153     return shift ? 31 : (2 << IsQuad) - 1;
1154   case NeonTypeFlags::Int64:
1155   case NeonTypeFlags::Poly64:
1156     return shift ? 63 : (1 << IsQuad) - 1;
1157   case NeonTypeFlags::Poly128:
1158     return shift ? 127 : (1 << IsQuad) - 1;
1159   case NeonTypeFlags::Float16:
1160     assert(!shift && "cannot shift float types!");
1161     return (4 << IsQuad) - 1;
1162   case NeonTypeFlags::Float32:
1163     assert(!shift && "cannot shift float types!");
1164     return (2 << IsQuad) - 1;
1165   case NeonTypeFlags::Float64:
1166     assert(!shift && "cannot shift float types!");
1167     return (1 << IsQuad) - 1;
1168   }
1169   llvm_unreachable("Invalid NeonTypeFlag!");
1170 }
1171
1172 /// getNeonEltType - Return the QualType corresponding to the elements of
1173 /// the vector type specified by the NeonTypeFlags.  This is used to check
1174 /// the pointer arguments for Neon load/store intrinsics.
1175 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1176                                bool IsPolyUnsigned, bool IsInt64Long) {
1177   switch (Flags.getEltType()) {
1178   case NeonTypeFlags::Int8:
1179     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180   case NeonTypeFlags::Int16:
1181     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182   case NeonTypeFlags::Int32:
1183     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184   case NeonTypeFlags::Int64:
1185     if (IsInt64Long)
1186       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187     else
1188       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189                                 : Context.LongLongTy;
1190   case NeonTypeFlags::Poly8:
1191     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1192   case NeonTypeFlags::Poly16:
1193     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1194   case NeonTypeFlags::Poly64:
1195     if (IsInt64Long)
1196       return Context.UnsignedLongTy;
1197     else
1198       return Context.UnsignedLongLongTy;
1199   case NeonTypeFlags::Poly128:
1200     break;
1201   case NeonTypeFlags::Float16:
1202     return Context.HalfTy;
1203   case NeonTypeFlags::Float32:
1204     return Context.FloatTy;
1205   case NeonTypeFlags::Float64:
1206     return Context.DoubleTy;
1207   }
1208   llvm_unreachable("Invalid NeonTypeFlag!");
1209 }
1210
1211 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1212   llvm::APSInt Result;
1213   uint64_t mask = 0;
1214   unsigned TV = 0;
1215   int PtrArgNum = -1;
1216   bool HasConstPtr = false;
1217   switch (BuiltinID) {
1218 #define GET_NEON_OVERLOAD_CHECK
1219 #include "clang/Basic/arm_neon.inc"
1220 #undef GET_NEON_OVERLOAD_CHECK
1221   }
1222
1223   // For NEON intrinsics which are overloaded on vector element type, validate
1224   // the immediate which specifies which variant to emit.
1225   unsigned ImmArg = TheCall->getNumArgs()-1;
1226   if (mask) {
1227     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228       return true;
1229
1230     TV = Result.getLimitedValue(64);
1231     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1233         << TheCall->getArg(ImmArg)->getSourceRange();
1234   }
1235
1236   if (PtrArgNum >= 0) {
1237     // Check that pointer arguments have the specified type.
1238     Expr *Arg = TheCall->getArg(PtrArgNum);
1239     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240       Arg = ICE->getSubExpr();
1241     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242     QualType RHSTy = RHS.get()->getType();
1243
1244     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1245     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1246     bool IsInt64Long =
1247         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1248     QualType EltTy =
1249         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1250     if (HasConstPtr)
1251       EltTy = EltTy.withConst();
1252     QualType LHSTy = Context.getPointerType(EltTy);
1253     AssignConvertType ConvTy;
1254     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255     if (RHS.isInvalid())
1256       return true;
1257     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258                                  RHS.get(), AA_Assigning))
1259       return true;
1260   }
1261
1262   // For NEON intrinsics which take an immediate value as part of the
1263   // instruction, range check them here.
1264   unsigned i = 0, l = 0, u = 0;
1265   switch (BuiltinID) {
1266   default:
1267     return false;
1268 #define GET_NEON_IMMEDIATE_CHECK
1269 #include "clang/Basic/arm_neon.inc"
1270 #undef GET_NEON_IMMEDIATE_CHECK
1271   }
1272
1273   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1274 }
1275
1276 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277                                         unsigned MaxWidth) {
1278   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1279           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1280           BuiltinID == ARM::BI__builtin_arm_strex ||
1281           BuiltinID == ARM::BI__builtin_arm_stlex ||
1282           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1283           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284           BuiltinID == AArch64::BI__builtin_arm_strex ||
1285           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1286          "unexpected ARM builtin");
1287   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1288                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1291
1292   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1293
1294   // Ensure that we have the proper number of arguments.
1295   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1296     return true;
1297
1298   // Inspect the pointer argument of the atomic builtin.  This should always be
1299   // a pointer type, whose element is an integral scalar or pointer type.
1300   // Because it is a pointer type, we don't have to worry about any implicit
1301   // casts here.
1302   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304   if (PointerArgRes.isInvalid())
1305     return true;
1306   PointerArg = PointerArgRes.get();
1307
1308   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1309   if (!pointerType) {
1310     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311       << PointerArg->getType() << PointerArg->getSourceRange();
1312     return true;
1313   }
1314
1315   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316   // task is to insert the appropriate casts into the AST. First work out just
1317   // what the appropriate type is.
1318   QualType ValType = pointerType->getPointeeType();
1319   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1320   if (IsLdrex)
1321     AddrType.addConst();
1322
1323   // Issue a warning if the cast is dodgy.
1324   CastKind CastNeeded = CK_NoOp;
1325   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326     CastNeeded = CK_BitCast;
1327     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328       << PointerArg->getType()
1329       << Context.getPointerType(AddrType)
1330       << AA_Passing << PointerArg->getSourceRange();
1331   }
1332
1333   // Finally, do the cast and replace the argument with the corrected version.
1334   AddrType = Context.getPointerType(AddrType);
1335   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336   if (PointerArgRes.isInvalid())
1337     return true;
1338   PointerArg = PointerArgRes.get();
1339
1340   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1341
1342   // In general, we allow ints, floats and pointers to be loaded and stored.
1343   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346       << PointerArg->getType() << PointerArg->getSourceRange();
1347     return true;
1348   }
1349
1350   // But ARM doesn't have instructions to deal with 128-bit versions.
1351   if (Context.getTypeSize(ValType) > MaxWidth) {
1352     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1353     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354       << PointerArg->getType() << PointerArg->getSourceRange();
1355     return true;
1356   }
1357
1358   switch (ValType.getObjCLifetime()) {
1359   case Qualifiers::OCL_None:
1360   case Qualifiers::OCL_ExplicitNone:
1361     // okay
1362     break;
1363
1364   case Qualifiers::OCL_Weak:
1365   case Qualifiers::OCL_Strong:
1366   case Qualifiers::OCL_Autoreleasing:
1367     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368       << ValType << PointerArg->getSourceRange();
1369     return true;
1370   }
1371
1372   if (IsLdrex) {
1373     TheCall->setType(ValType);
1374     return false;
1375   }
1376
1377   // Initialize the argument to be stored.
1378   ExprResult ValArg = TheCall->getArg(0);
1379   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380       Context, ValType, /*consume*/ false);
1381   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382   if (ValArg.isInvalid())
1383     return true;
1384   TheCall->setArg(0, ValArg.get());
1385
1386   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387   // but the custom checker bypasses all default analysis.
1388   TheCall->setType(Context.IntTy);
1389   return false;
1390 }
1391
1392 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1393   llvm::APSInt Result;
1394
1395   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1396       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397       BuiltinID == ARM::BI__builtin_arm_strex ||
1398       BuiltinID == ARM::BI__builtin_arm_stlex) {
1399     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1400   }
1401
1402   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1405   }
1406
1407   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408       BuiltinID == ARM::BI__builtin_arm_wsr64)
1409     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410
1411   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413       BuiltinID == ARM::BI__builtin_arm_wsr ||
1414       BuiltinID == ARM::BI__builtin_arm_wsrp)
1415     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416
1417   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1418     return true;
1419
1420   // For intrinsics which take an immediate value as part of the instruction,
1421   // range check them here.
1422   unsigned i = 0, l = 0, u = 0;
1423   switch (BuiltinID) {
1424   default: return false;
1425   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1427   case ARM::BI__builtin_arm_vcvtr_f:
1428   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1429   case ARM::BI__builtin_arm_dmb:
1430   case ARM::BI__builtin_arm_dsb:
1431   case ARM::BI__builtin_arm_isb:
1432   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1433   }
1434
1435   // FIXME: VFP Intrinsics should error if VFP not present.
1436   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1437 }
1438
1439 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1440                                          CallExpr *TheCall) {
1441   llvm::APSInt Result;
1442
1443   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1444       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445       BuiltinID == AArch64::BI__builtin_arm_strex ||
1446       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1447     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448   }
1449
1450   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455   }
1456
1457   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1459     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1460
1461   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466
1467   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468     return true;
1469
1470   // For intrinsics which take an immediate value as part of the instruction,
1471   // range check them here.
1472   unsigned i = 0, l = 0, u = 0;
1473   switch (BuiltinID) {
1474   default: return false;
1475   case AArch64::BI__builtin_arm_dmb:
1476   case AArch64::BI__builtin_arm_dsb:
1477   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478   }
1479
1480   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1481 }
1482
1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485 // ordering for DSP is unspecified. MSA is ordered by the data format used
1486 // by the underlying instruction i.e., df/m, df/n and then by size.
1487 //
1488 // FIXME: The size tests here should instead be tablegen'd along with the
1489 //        definitions from include/clang/Basic/BuiltinsMips.def.
1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491 //        be too.
1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1493   unsigned i = 0, l = 0, u = 0, m = 0;
1494   switch (BuiltinID) {
1495   default: return false;
1496   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1498   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1503   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504   // df/m field.
1505   // These intrinsics take an unsigned 3 bit immediate.
1506   case Mips::BI__builtin_msa_bclri_b:
1507   case Mips::BI__builtin_msa_bnegi_b:
1508   case Mips::BI__builtin_msa_bseti_b:
1509   case Mips::BI__builtin_msa_sat_s_b:
1510   case Mips::BI__builtin_msa_sat_u_b:
1511   case Mips::BI__builtin_msa_slli_b:
1512   case Mips::BI__builtin_msa_srai_b:
1513   case Mips::BI__builtin_msa_srari_b:
1514   case Mips::BI__builtin_msa_srli_b:
1515   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516   case Mips::BI__builtin_msa_binsli_b:
1517   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518   // These intrinsics take an unsigned 4 bit immediate.
1519   case Mips::BI__builtin_msa_bclri_h:
1520   case Mips::BI__builtin_msa_bnegi_h:
1521   case Mips::BI__builtin_msa_bseti_h:
1522   case Mips::BI__builtin_msa_sat_s_h:
1523   case Mips::BI__builtin_msa_sat_u_h:
1524   case Mips::BI__builtin_msa_slli_h:
1525   case Mips::BI__builtin_msa_srai_h:
1526   case Mips::BI__builtin_msa_srari_h:
1527   case Mips::BI__builtin_msa_srli_h:
1528   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529   case Mips::BI__builtin_msa_binsli_h:
1530   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531   // These intrinsics take an unsigned 5 bit immedate.
1532   // The first block of intrinsics actually have an unsigned 5 bit field,
1533   // not a df/n field.
1534   case Mips::BI__builtin_msa_clei_u_b:
1535   case Mips::BI__builtin_msa_clei_u_h:
1536   case Mips::BI__builtin_msa_clei_u_w:
1537   case Mips::BI__builtin_msa_clei_u_d:
1538   case Mips::BI__builtin_msa_clti_u_b:
1539   case Mips::BI__builtin_msa_clti_u_h:
1540   case Mips::BI__builtin_msa_clti_u_w:
1541   case Mips::BI__builtin_msa_clti_u_d:
1542   case Mips::BI__builtin_msa_maxi_u_b:
1543   case Mips::BI__builtin_msa_maxi_u_h:
1544   case Mips::BI__builtin_msa_maxi_u_w:
1545   case Mips::BI__builtin_msa_maxi_u_d:
1546   case Mips::BI__builtin_msa_mini_u_b:
1547   case Mips::BI__builtin_msa_mini_u_h:
1548   case Mips::BI__builtin_msa_mini_u_w:
1549   case Mips::BI__builtin_msa_mini_u_d:
1550   case Mips::BI__builtin_msa_addvi_b:
1551   case Mips::BI__builtin_msa_addvi_h:
1552   case Mips::BI__builtin_msa_addvi_w:
1553   case Mips::BI__builtin_msa_addvi_d:
1554   case Mips::BI__builtin_msa_bclri_w:
1555   case Mips::BI__builtin_msa_bnegi_w:
1556   case Mips::BI__builtin_msa_bseti_w:
1557   case Mips::BI__builtin_msa_sat_s_w:
1558   case Mips::BI__builtin_msa_sat_u_w:
1559   case Mips::BI__builtin_msa_slli_w:
1560   case Mips::BI__builtin_msa_srai_w:
1561   case Mips::BI__builtin_msa_srari_w:
1562   case Mips::BI__builtin_msa_srli_w:
1563   case Mips::BI__builtin_msa_srlri_w:
1564   case Mips::BI__builtin_msa_subvi_b:
1565   case Mips::BI__builtin_msa_subvi_h:
1566   case Mips::BI__builtin_msa_subvi_w:
1567   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568   case Mips::BI__builtin_msa_binsli_w:
1569   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570   // These intrinsics take an unsigned 6 bit immediate.
1571   case Mips::BI__builtin_msa_bclri_d:
1572   case Mips::BI__builtin_msa_bnegi_d:
1573   case Mips::BI__builtin_msa_bseti_d:
1574   case Mips::BI__builtin_msa_sat_s_d:
1575   case Mips::BI__builtin_msa_sat_u_d:
1576   case Mips::BI__builtin_msa_slli_d:
1577   case Mips::BI__builtin_msa_srai_d:
1578   case Mips::BI__builtin_msa_srari_d:
1579   case Mips::BI__builtin_msa_srli_d:
1580   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581   case Mips::BI__builtin_msa_binsli_d:
1582   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583   // These intrinsics take a signed 5 bit immediate.
1584   case Mips::BI__builtin_msa_ceqi_b:
1585   case Mips::BI__builtin_msa_ceqi_h:
1586   case Mips::BI__builtin_msa_ceqi_w:
1587   case Mips::BI__builtin_msa_ceqi_d:
1588   case Mips::BI__builtin_msa_clti_s_b:
1589   case Mips::BI__builtin_msa_clti_s_h:
1590   case Mips::BI__builtin_msa_clti_s_w:
1591   case Mips::BI__builtin_msa_clti_s_d:
1592   case Mips::BI__builtin_msa_clei_s_b:
1593   case Mips::BI__builtin_msa_clei_s_h:
1594   case Mips::BI__builtin_msa_clei_s_w:
1595   case Mips::BI__builtin_msa_clei_s_d:
1596   case Mips::BI__builtin_msa_maxi_s_b:
1597   case Mips::BI__builtin_msa_maxi_s_h:
1598   case Mips::BI__builtin_msa_maxi_s_w:
1599   case Mips::BI__builtin_msa_maxi_s_d:
1600   case Mips::BI__builtin_msa_mini_s_b:
1601   case Mips::BI__builtin_msa_mini_s_h:
1602   case Mips::BI__builtin_msa_mini_s_w:
1603   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604   // These intrinsics take an unsigned 8 bit immediate.
1605   case Mips::BI__builtin_msa_andi_b:
1606   case Mips::BI__builtin_msa_nori_b:
1607   case Mips::BI__builtin_msa_ori_b:
1608   case Mips::BI__builtin_msa_shf_b:
1609   case Mips::BI__builtin_msa_shf_h:
1610   case Mips::BI__builtin_msa_shf_w:
1611   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612   case Mips::BI__builtin_msa_bseli_b:
1613   case Mips::BI__builtin_msa_bmnzi_b:
1614   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615   // df/n format
1616   // These intrinsics take an unsigned 4 bit immediate.
1617   case Mips::BI__builtin_msa_copy_s_b:
1618   case Mips::BI__builtin_msa_copy_u_b:
1619   case Mips::BI__builtin_msa_insve_b:
1620   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621   case Mips::BI__builtin_msa_sld_b:
1622   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623   // These intrinsics take an unsigned 3 bit immediate.
1624   case Mips::BI__builtin_msa_copy_s_h:
1625   case Mips::BI__builtin_msa_copy_u_h:
1626   case Mips::BI__builtin_msa_insve_h:
1627   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628   case Mips::BI__builtin_msa_sld_h:
1629   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630   // These intrinsics take an unsigned 2 bit immediate.
1631   case Mips::BI__builtin_msa_copy_s_w:
1632   case Mips::BI__builtin_msa_copy_u_w:
1633   case Mips::BI__builtin_msa_insve_w:
1634   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635   case Mips::BI__builtin_msa_sld_w:
1636   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637   // These intrinsics take an unsigned 1 bit immediate.
1638   case Mips::BI__builtin_msa_copy_s_d:
1639   case Mips::BI__builtin_msa_copy_u_d:
1640   case Mips::BI__builtin_msa_insve_d:
1641   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642   case Mips::BI__builtin_msa_sld_d:
1643   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644   // Memory offsets and immediate loads.
1645   // These intrinsics take a signed 10 bit immediate.
1646   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647   case Mips::BI__builtin_msa_ldi_h:
1648   case Mips::BI__builtin_msa_ldi_w:
1649   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1658   }
1659
1660   if (!m)
1661     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1662
1663   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1665 }
1666
1667 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668   unsigned i = 0, l = 0, u = 0;
1669   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670                       BuiltinID == PPC::BI__builtin_divdeu ||
1671                       BuiltinID == PPC::BI__builtin_bpermd;
1672   bool IsTarget64Bit = Context.getTargetInfo()
1673                               .getTypeWidth(Context
1674                                             .getTargetInfo()
1675                                             .getIntPtrType()) == 64;
1676   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677                        BuiltinID == PPC::BI__builtin_divweu ||
1678                        BuiltinID == PPC::BI__builtin_divde ||
1679                        BuiltinID == PPC::BI__builtin_divdeu;
1680
1681   if (Is64BitBltin && !IsTarget64Bit)
1682       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683              << TheCall->getSourceRange();
1684
1685   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686       (BuiltinID == PPC::BI__builtin_bpermd &&
1687        !Context.getTargetInfo().hasFeature("bpermd")))
1688     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689            << TheCall->getSourceRange();
1690
1691   switch (BuiltinID) {
1692   default: return false;
1693   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697   case PPC::BI__builtin_tbegin:
1698   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700   case PPC::BI__builtin_tabortwc:
1701   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702   case PPC::BI__builtin_tabortwci:
1703   case PPC::BI__builtin_tabortdci:
1704     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1706   }
1707   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708 }
1709
1710 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711                                            CallExpr *TheCall) {
1712   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713     Expr *Arg = TheCall->getArg(0);
1714     llvm::APSInt AbortCode(32);
1715     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718              << Arg->getSourceRange();
1719   }
1720
1721   // For intrinsics which take an immediate value as part of the instruction,
1722   // range check them here.
1723   unsigned i = 0, l = 0, u = 0;
1724   switch (BuiltinID) {
1725   default: return false;
1726   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727   case SystemZ::BI__builtin_s390_verimb:
1728   case SystemZ::BI__builtin_s390_verimh:
1729   case SystemZ::BI__builtin_s390_verimf:
1730   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731   case SystemZ::BI__builtin_s390_vfaeb:
1732   case SystemZ::BI__builtin_s390_vfaeh:
1733   case SystemZ::BI__builtin_s390_vfaef:
1734   case SystemZ::BI__builtin_s390_vfaebs:
1735   case SystemZ::BI__builtin_s390_vfaehs:
1736   case SystemZ::BI__builtin_s390_vfaefs:
1737   case SystemZ::BI__builtin_s390_vfaezb:
1738   case SystemZ::BI__builtin_s390_vfaezh:
1739   case SystemZ::BI__builtin_s390_vfaezf:
1740   case SystemZ::BI__builtin_s390_vfaezbs:
1741   case SystemZ::BI__builtin_s390_vfaezhs:
1742   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743   case SystemZ::BI__builtin_s390_vfidb:
1744     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750   case SystemZ::BI__builtin_s390_vstrcb:
1751   case SystemZ::BI__builtin_s390_vstrch:
1752   case SystemZ::BI__builtin_s390_vstrcf:
1753   case SystemZ::BI__builtin_s390_vstrczb:
1754   case SystemZ::BI__builtin_s390_vstrczh:
1755   case SystemZ::BI__builtin_s390_vstrczf:
1756   case SystemZ::BI__builtin_s390_vstrcbs:
1757   case SystemZ::BI__builtin_s390_vstrchs:
1758   case SystemZ::BI__builtin_s390_vstrcfs:
1759   case SystemZ::BI__builtin_s390_vstrczbs:
1760   case SystemZ::BI__builtin_s390_vstrczhs:
1761   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1762   }
1763   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1764 }
1765
1766 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767 /// This checks that the target supports __builtin_cpu_supports and
1768 /// that the string argument is constant and valid.
1769 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770   Expr *Arg = TheCall->getArg(0);
1771
1772   // Check if the argument is a string literal.
1773   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775            << Arg->getSourceRange();
1776
1777   // Check the contents of the string.
1778   StringRef Feature =
1779       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782            << Arg->getSourceRange();
1783   return false;
1784 }
1785
1786 // Check if the rounding mode is legal.
1787 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788   // Indicates if this instruction has rounding control or just SAE.
1789   bool HasRC = false;
1790
1791   unsigned ArgNum = 0;
1792   switch (BuiltinID) {
1793   default:
1794     return false;
1795   case X86::BI__builtin_ia32_vcvttsd2si32:
1796   case X86::BI__builtin_ia32_vcvttsd2si64:
1797   case X86::BI__builtin_ia32_vcvttsd2usi32:
1798   case X86::BI__builtin_ia32_vcvttsd2usi64:
1799   case X86::BI__builtin_ia32_vcvttss2si32:
1800   case X86::BI__builtin_ia32_vcvttss2si64:
1801   case X86::BI__builtin_ia32_vcvttss2usi32:
1802   case X86::BI__builtin_ia32_vcvttss2usi64:
1803     ArgNum = 1;
1804     break;
1805   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814   case X86::BI__builtin_ia32_exp2pd_mask:
1815   case X86::BI__builtin_ia32_exp2ps_mask:
1816   case X86::BI__builtin_ia32_getexppd512_mask:
1817   case X86::BI__builtin_ia32_getexpps512_mask:
1818   case X86::BI__builtin_ia32_rcp28pd_mask:
1819   case X86::BI__builtin_ia32_rcp28ps_mask:
1820   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822   case X86::BI__builtin_ia32_vcomisd:
1823   case X86::BI__builtin_ia32_vcomiss:
1824   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1825     ArgNum = 3;
1826     break;
1827   case X86::BI__builtin_ia32_cmppd512_mask:
1828   case X86::BI__builtin_ia32_cmpps512_mask:
1829   case X86::BI__builtin_ia32_cmpsd_mask:
1830   case X86::BI__builtin_ia32_cmpss_mask:
1831   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1832   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833   case X86::BI__builtin_ia32_getexpss128_round_mask:
1834   case X86::BI__builtin_ia32_maxpd512_mask:
1835   case X86::BI__builtin_ia32_maxps512_mask:
1836   case X86::BI__builtin_ia32_maxsd_round_mask:
1837   case X86::BI__builtin_ia32_maxss_round_mask:
1838   case X86::BI__builtin_ia32_minpd512_mask:
1839   case X86::BI__builtin_ia32_minps512_mask:
1840   case X86::BI__builtin_ia32_minsd_round_mask:
1841   case X86::BI__builtin_ia32_minss_round_mask:
1842   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844   case X86::BI__builtin_ia32_reducepd512_mask:
1845   case X86::BI__builtin_ia32_reduceps512_mask:
1846   case X86::BI__builtin_ia32_rndscalepd_mask:
1847   case X86::BI__builtin_ia32_rndscaleps_mask:
1848   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1850     ArgNum = 4;
1851     break;
1852   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1853   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1854   case X86::BI__builtin_ia32_fixupimmps512_mask:
1855   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1856   case X86::BI__builtin_ia32_fixupimmsd_mask:
1857   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1858   case X86::BI__builtin_ia32_fixupimmss_mask:
1859   case X86::BI__builtin_ia32_fixupimmss_maskz:
1860   case X86::BI__builtin_ia32_rangepd512_mask:
1861   case X86::BI__builtin_ia32_rangeps512_mask:
1862   case X86::BI__builtin_ia32_rangesd128_round_mask:
1863   case X86::BI__builtin_ia32_rangess128_round_mask:
1864   case X86::BI__builtin_ia32_reducesd_mask:
1865   case X86::BI__builtin_ia32_reducess_mask:
1866   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867   case X86::BI__builtin_ia32_rndscaless_round_mask:
1868     ArgNum = 5;
1869     break;
1870   case X86::BI__builtin_ia32_vcvtsd2si64:
1871   case X86::BI__builtin_ia32_vcvtsd2si32:
1872   case X86::BI__builtin_ia32_vcvtsd2usi32:
1873   case X86::BI__builtin_ia32_vcvtsd2usi64:
1874   case X86::BI__builtin_ia32_vcvtss2si32:
1875   case X86::BI__builtin_ia32_vcvtss2si64:
1876   case X86::BI__builtin_ia32_vcvtss2usi32:
1877   case X86::BI__builtin_ia32_vcvtss2usi64:
1878     ArgNum = 1;
1879     HasRC = true;
1880     break;
1881   case X86::BI__builtin_ia32_cvtsi2sd64:
1882   case X86::BI__builtin_ia32_cvtsi2ss32:
1883   case X86::BI__builtin_ia32_cvtsi2ss64:
1884   case X86::BI__builtin_ia32_cvtusi2sd64:
1885   case X86::BI__builtin_ia32_cvtusi2ss32:
1886   case X86::BI__builtin_ia32_cvtusi2ss64:
1887     ArgNum = 2;
1888     HasRC = true;
1889     break;
1890   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1901   case X86::BI__builtin_ia32_sqrtpd512_mask:
1902   case X86::BI__builtin_ia32_sqrtps512_mask:
1903     ArgNum = 3;
1904     HasRC = true;
1905     break;
1906   case X86::BI__builtin_ia32_addpd512_mask:
1907   case X86::BI__builtin_ia32_addps512_mask:
1908   case X86::BI__builtin_ia32_divpd512_mask:
1909   case X86::BI__builtin_ia32_divps512_mask:
1910   case X86::BI__builtin_ia32_mulpd512_mask:
1911   case X86::BI__builtin_ia32_mulps512_mask:
1912   case X86::BI__builtin_ia32_subpd512_mask:
1913   case X86::BI__builtin_ia32_subps512_mask:
1914   case X86::BI__builtin_ia32_addss_round_mask:
1915   case X86::BI__builtin_ia32_addsd_round_mask:
1916   case X86::BI__builtin_ia32_divss_round_mask:
1917   case X86::BI__builtin_ia32_divsd_round_mask:
1918   case X86::BI__builtin_ia32_mulss_round_mask:
1919   case X86::BI__builtin_ia32_mulsd_round_mask:
1920   case X86::BI__builtin_ia32_subss_round_mask:
1921   case X86::BI__builtin_ia32_subsd_round_mask:
1922   case X86::BI__builtin_ia32_scalefpd512_mask:
1923   case X86::BI__builtin_ia32_scalefps512_mask:
1924   case X86::BI__builtin_ia32_scalefsd_round_mask:
1925   case X86::BI__builtin_ia32_scalefss_round_mask:
1926   case X86::BI__builtin_ia32_getmantpd512_mask:
1927   case X86::BI__builtin_ia32_getmantps512_mask:
1928   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929   case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930   case X86::BI__builtin_ia32_sqrtss_round_mask:
1931   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934   case X86::BI__builtin_ia32_vfmaddps512_mask:
1935   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956   case X86::BI__builtin_ia32_vfmaddss3_mask:
1957   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1959     ArgNum = 4;
1960     HasRC = true;
1961     break;
1962   case X86::BI__builtin_ia32_getmantsd_round_mask:
1963   case X86::BI__builtin_ia32_getmantss_round_mask:
1964     ArgNum = 5;
1965     HasRC = true;
1966     break;
1967   }
1968
1969   llvm::APSInt Result;
1970
1971   // We can't check the value of a dependent argument.
1972   Expr *Arg = TheCall->getArg(ArgNum);
1973   if (Arg->isTypeDependent() || Arg->isValueDependent())
1974     return false;
1975
1976   // Check constant-ness first.
1977   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1978     return true;
1979
1980   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982   // combined with ROUND_NO_EXC.
1983   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984       Result == 8/*ROUND_NO_EXC*/ ||
1985       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1986     return false;
1987
1988   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989     << Arg->getSourceRange();
1990 }
1991
1992 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993   if (BuiltinID == X86::BI__builtin_cpu_supports)
1994     return SemaBuiltinCpuSupports(*this, TheCall);
1995
1996   if (BuiltinID == X86::BI__builtin_ms_va_start)
1997     return SemaBuiltinMSVAStart(TheCall);
1998
1999   // If the intrinsic has rounding or SAE make sure its valid.
2000   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2001     return true;
2002
2003   // For intrinsics which take an immediate value as part of the instruction,
2004   // range check them here.
2005   int i = 0, l = 0, u = 0;
2006   switch (BuiltinID) {
2007   default:
2008     return false;
2009   case X86::BI_mm_prefetch:
2010     i = 1; l = 0; u = 3;
2011     break;
2012   case X86::BI__builtin_ia32_sha1rnds4:
2013   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2017     i = 2; l = 0; u = 3;
2018     break;
2019   case X86::BI__builtin_ia32_vpermil2pd:
2020   case X86::BI__builtin_ia32_vpermil2pd256:
2021   case X86::BI__builtin_ia32_vpermil2ps:
2022   case X86::BI__builtin_ia32_vpermil2ps256:
2023     i = 3; l = 0; u = 3;
2024     break;
2025   case X86::BI__builtin_ia32_cmpb128_mask:
2026   case X86::BI__builtin_ia32_cmpw128_mask:
2027   case X86::BI__builtin_ia32_cmpd128_mask:
2028   case X86::BI__builtin_ia32_cmpq128_mask:
2029   case X86::BI__builtin_ia32_cmpb256_mask:
2030   case X86::BI__builtin_ia32_cmpw256_mask:
2031   case X86::BI__builtin_ia32_cmpd256_mask:
2032   case X86::BI__builtin_ia32_cmpq256_mask:
2033   case X86::BI__builtin_ia32_cmpb512_mask:
2034   case X86::BI__builtin_ia32_cmpw512_mask:
2035   case X86::BI__builtin_ia32_cmpd512_mask:
2036   case X86::BI__builtin_ia32_cmpq512_mask:
2037   case X86::BI__builtin_ia32_ucmpb128_mask:
2038   case X86::BI__builtin_ia32_ucmpw128_mask:
2039   case X86::BI__builtin_ia32_ucmpd128_mask:
2040   case X86::BI__builtin_ia32_ucmpq128_mask:
2041   case X86::BI__builtin_ia32_ucmpb256_mask:
2042   case X86::BI__builtin_ia32_ucmpw256_mask:
2043   case X86::BI__builtin_ia32_ucmpd256_mask:
2044   case X86::BI__builtin_ia32_ucmpq256_mask:
2045   case X86::BI__builtin_ia32_ucmpb512_mask:
2046   case X86::BI__builtin_ia32_ucmpw512_mask:
2047   case X86::BI__builtin_ia32_ucmpd512_mask:
2048   case X86::BI__builtin_ia32_ucmpq512_mask:
2049   case X86::BI__builtin_ia32_vpcomub:
2050   case X86::BI__builtin_ia32_vpcomuw:
2051   case X86::BI__builtin_ia32_vpcomud:
2052   case X86::BI__builtin_ia32_vpcomuq:
2053   case X86::BI__builtin_ia32_vpcomb:
2054   case X86::BI__builtin_ia32_vpcomw:
2055   case X86::BI__builtin_ia32_vpcomd:
2056   case X86::BI__builtin_ia32_vpcomq:
2057     i = 2; l = 0; u = 7;
2058     break;
2059   case X86::BI__builtin_ia32_roundps:
2060   case X86::BI__builtin_ia32_roundpd:
2061   case X86::BI__builtin_ia32_roundps256:
2062   case X86::BI__builtin_ia32_roundpd256:
2063     i = 1; l = 0; u = 15;
2064     break;
2065   case X86::BI__builtin_ia32_roundss:
2066   case X86::BI__builtin_ia32_roundsd:
2067   case X86::BI__builtin_ia32_rangepd128_mask:
2068   case X86::BI__builtin_ia32_rangepd256_mask:
2069   case X86::BI__builtin_ia32_rangepd512_mask:
2070   case X86::BI__builtin_ia32_rangeps128_mask:
2071   case X86::BI__builtin_ia32_rangeps256_mask:
2072   case X86::BI__builtin_ia32_rangeps512_mask:
2073   case X86::BI__builtin_ia32_getmantsd_round_mask:
2074   case X86::BI__builtin_ia32_getmantss_round_mask:
2075     i = 2; l = 0; u = 15;
2076     break;
2077   case X86::BI__builtin_ia32_cmpps:
2078   case X86::BI__builtin_ia32_cmpss:
2079   case X86::BI__builtin_ia32_cmppd:
2080   case X86::BI__builtin_ia32_cmpsd:
2081   case X86::BI__builtin_ia32_cmpps256:
2082   case X86::BI__builtin_ia32_cmppd256:
2083   case X86::BI__builtin_ia32_cmpps128_mask:
2084   case X86::BI__builtin_ia32_cmppd128_mask:
2085   case X86::BI__builtin_ia32_cmpps256_mask:
2086   case X86::BI__builtin_ia32_cmppd256_mask:
2087   case X86::BI__builtin_ia32_cmpps512_mask:
2088   case X86::BI__builtin_ia32_cmppd512_mask:
2089   case X86::BI__builtin_ia32_cmpsd_mask:
2090   case X86::BI__builtin_ia32_cmpss_mask:
2091     i = 2; l = 0; u = 31;
2092     break;
2093   case X86::BI__builtin_ia32_xabort:
2094     i = 0; l = -128; u = 255;
2095     break;
2096   case X86::BI__builtin_ia32_pshufw:
2097   case X86::BI__builtin_ia32_aeskeygenassist128:
2098     i = 1; l = -128; u = 255;
2099     break;
2100   case X86::BI__builtin_ia32_vcvtps2ph:
2101   case X86::BI__builtin_ia32_vcvtps2ph256:
2102   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106   case X86::BI__builtin_ia32_rndscaleps_mask:
2107   case X86::BI__builtin_ia32_rndscalepd_mask:
2108   case X86::BI__builtin_ia32_reducepd128_mask:
2109   case X86::BI__builtin_ia32_reducepd256_mask:
2110   case X86::BI__builtin_ia32_reducepd512_mask:
2111   case X86::BI__builtin_ia32_reduceps128_mask:
2112   case X86::BI__builtin_ia32_reduceps256_mask:
2113   case X86::BI__builtin_ia32_reduceps512_mask:
2114   case X86::BI__builtin_ia32_prold512_mask:
2115   case X86::BI__builtin_ia32_prolq512_mask:
2116   case X86::BI__builtin_ia32_prold128_mask:
2117   case X86::BI__builtin_ia32_prold256_mask:
2118   case X86::BI__builtin_ia32_prolq128_mask:
2119   case X86::BI__builtin_ia32_prolq256_mask:
2120   case X86::BI__builtin_ia32_prord128_mask:
2121   case X86::BI__builtin_ia32_prord256_mask:
2122   case X86::BI__builtin_ia32_prorq128_mask:
2123   case X86::BI__builtin_ia32_prorq256_mask:
2124   case X86::BI__builtin_ia32_fpclasspd128_mask:
2125   case X86::BI__builtin_ia32_fpclasspd256_mask:
2126   case X86::BI__builtin_ia32_fpclassps128_mask:
2127   case X86::BI__builtin_ia32_fpclassps256_mask:
2128   case X86::BI__builtin_ia32_fpclassps512_mask:
2129   case X86::BI__builtin_ia32_fpclasspd512_mask:
2130   case X86::BI__builtin_ia32_fpclasssd_mask:
2131   case X86::BI__builtin_ia32_fpclassss_mask:
2132     i = 1; l = 0; u = 255;
2133     break;
2134   case X86::BI__builtin_ia32_palignr:
2135   case X86::BI__builtin_ia32_insertps128:
2136   case X86::BI__builtin_ia32_dpps:
2137   case X86::BI__builtin_ia32_dppd:
2138   case X86::BI__builtin_ia32_dpps256:
2139   case X86::BI__builtin_ia32_mpsadbw128:
2140   case X86::BI__builtin_ia32_mpsadbw256:
2141   case X86::BI__builtin_ia32_pcmpistrm128:
2142   case X86::BI__builtin_ia32_pcmpistri128:
2143   case X86::BI__builtin_ia32_pcmpistria128:
2144   case X86::BI__builtin_ia32_pcmpistric128:
2145   case X86::BI__builtin_ia32_pcmpistrio128:
2146   case X86::BI__builtin_ia32_pcmpistris128:
2147   case X86::BI__builtin_ia32_pcmpistriz128:
2148   case X86::BI__builtin_ia32_pclmulqdq128:
2149   case X86::BI__builtin_ia32_vperm2f128_pd256:
2150   case X86::BI__builtin_ia32_vperm2f128_ps256:
2151   case X86::BI__builtin_ia32_vperm2f128_si256:
2152   case X86::BI__builtin_ia32_permti256:
2153     i = 2; l = -128; u = 255;
2154     break;
2155   case X86::BI__builtin_ia32_palignr128:
2156   case X86::BI__builtin_ia32_palignr256:
2157   case X86::BI__builtin_ia32_palignr512_mask:
2158   case X86::BI__builtin_ia32_vcomisd:
2159   case X86::BI__builtin_ia32_vcomiss:
2160   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2161   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2162   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2163   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2164   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2165   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2166   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2167     i = 2; l = 0; u = 255;
2168     break;
2169   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2170   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2171   case X86::BI__builtin_ia32_fixupimmps512_mask:
2172   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2173   case X86::BI__builtin_ia32_fixupimmsd_mask:
2174   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2175   case X86::BI__builtin_ia32_fixupimmss_mask:
2176   case X86::BI__builtin_ia32_fixupimmss_maskz:
2177   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2178   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2179   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2180   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2181   case X86::BI__builtin_ia32_fixupimmps128_mask:
2182   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2183   case X86::BI__builtin_ia32_fixupimmps256_mask:
2184   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2185   case X86::BI__builtin_ia32_pternlogd512_mask:
2186   case X86::BI__builtin_ia32_pternlogd512_maskz:
2187   case X86::BI__builtin_ia32_pternlogq512_mask:
2188   case X86::BI__builtin_ia32_pternlogq512_maskz:
2189   case X86::BI__builtin_ia32_pternlogd128_mask:
2190   case X86::BI__builtin_ia32_pternlogd128_maskz:
2191   case X86::BI__builtin_ia32_pternlogd256_mask:
2192   case X86::BI__builtin_ia32_pternlogd256_maskz:
2193   case X86::BI__builtin_ia32_pternlogq128_mask:
2194   case X86::BI__builtin_ia32_pternlogq128_maskz:
2195   case X86::BI__builtin_ia32_pternlogq256_mask:
2196   case X86::BI__builtin_ia32_pternlogq256_maskz:
2197     i = 3; l = 0; u = 255;
2198     break;
2199   case X86::BI__builtin_ia32_pcmpestrm128:
2200   case X86::BI__builtin_ia32_pcmpestri128:
2201   case X86::BI__builtin_ia32_pcmpestria128:
2202   case X86::BI__builtin_ia32_pcmpestric128:
2203   case X86::BI__builtin_ia32_pcmpestrio128:
2204   case X86::BI__builtin_ia32_pcmpestris128:
2205   case X86::BI__builtin_ia32_pcmpestriz128:
2206     i = 4; l = -128; u = 255;
2207     break;
2208   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2209   case X86::BI__builtin_ia32_rndscaless_round_mask:
2210     i = 4; l = 0; u = 255;
2211     break;
2212   }
2213   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2214 }
2215
2216 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2217 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2218 /// Returns true when the format fits the function and the FormatStringInfo has
2219 /// been populated.
2220 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2221                                FormatStringInfo *FSI) {
2222   FSI->HasVAListArg = Format->getFirstArg() == 0;
2223   FSI->FormatIdx = Format->getFormatIdx() - 1;
2224   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2225
2226   // The way the format attribute works in GCC, the implicit this argument
2227   // of member functions is counted. However, it doesn't appear in our own
2228   // lists, so decrement format_idx in that case.
2229   if (IsCXXMember) {
2230     if(FSI->FormatIdx == 0)
2231       return false;
2232     --FSI->FormatIdx;
2233     if (FSI->FirstDataArg != 0)
2234       --FSI->FirstDataArg;
2235   }
2236   return true;
2237 }
2238
2239 /// Checks if a the given expression evaluates to null.
2240 ///
2241 /// \brief Returns true if the value evaluates to null.
2242 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2243   // If the expression has non-null type, it doesn't evaluate to null.
2244   if (auto nullability
2245         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2246     if (*nullability == NullabilityKind::NonNull)
2247       return false;
2248   }
2249
2250   // As a special case, transparent unions initialized with zero are
2251   // considered null for the purposes of the nonnull attribute.
2252   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2253     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2254       if (const CompoundLiteralExpr *CLE =
2255           dyn_cast<CompoundLiteralExpr>(Expr))
2256         if (const InitListExpr *ILE =
2257             dyn_cast<InitListExpr>(CLE->getInitializer()))
2258           Expr = ILE->getInit(0);
2259   }
2260
2261   bool Result;
2262   return (!Expr->isValueDependent() &&
2263           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2264           !Result);
2265 }
2266
2267 static void CheckNonNullArgument(Sema &S,
2268                                  const Expr *ArgExpr,
2269                                  SourceLocation CallSiteLoc) {
2270   if (CheckNonNullExpr(S, ArgExpr))
2271     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2272            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2273 }
2274
2275 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2276   FormatStringInfo FSI;
2277   if ((GetFormatStringType(Format) == FST_NSString) &&
2278       getFormatStringInfo(Format, false, &FSI)) {
2279     Idx = FSI.FormatIdx;
2280     return true;
2281   }
2282   return false;
2283 }
2284 /// \brief Diagnose use of %s directive in an NSString which is being passed
2285 /// as formatting string to formatting method.
2286 static void
2287 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2288                                         const NamedDecl *FDecl,
2289                                         Expr **Args,
2290                                         unsigned NumArgs) {
2291   unsigned Idx = 0;
2292   bool Format = false;
2293   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2294   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2295     Idx = 2;
2296     Format = true;
2297   }
2298   else
2299     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2300       if (S.GetFormatNSStringIdx(I, Idx)) {
2301         Format = true;
2302         break;
2303       }
2304     }
2305   if (!Format || NumArgs <= Idx)
2306     return;
2307   const Expr *FormatExpr = Args[Idx];
2308   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2309     FormatExpr = CSCE->getSubExpr();
2310   const StringLiteral *FormatString;
2311   if (const ObjCStringLiteral *OSL =
2312       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2313     FormatString = OSL->getString();
2314   else
2315     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2316   if (!FormatString)
2317     return;
2318   if (S.FormatStringHasSArg(FormatString)) {
2319     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2320       << "%s" << 1 << 1;
2321     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2322       << FDecl->getDeclName();
2323   }
2324 }
2325
2326 /// Determine whether the given type has a non-null nullability annotation.
2327 static bool isNonNullType(ASTContext &ctx, QualType type) {
2328   if (auto nullability = type->getNullability(ctx))
2329     return *nullability == NullabilityKind::NonNull;
2330      
2331   return false;
2332 }
2333
2334 static void CheckNonNullArguments(Sema &S,
2335                                   const NamedDecl *FDecl,
2336                                   const FunctionProtoType *Proto,
2337                                   ArrayRef<const Expr *> Args,
2338                                   SourceLocation CallSiteLoc) {
2339   assert((FDecl || Proto) && "Need a function declaration or prototype");
2340
2341   // Check the attributes attached to the method/function itself.
2342   llvm::SmallBitVector NonNullArgs;
2343   if (FDecl) {
2344     // Handle the nonnull attribute on the function/method declaration itself.
2345     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2346       if (!NonNull->args_size()) {
2347         // Easy case: all pointer arguments are nonnull.
2348         for (const auto *Arg : Args)
2349           if (S.isValidPointerAttrType(Arg->getType()))
2350             CheckNonNullArgument(S, Arg, CallSiteLoc);
2351         return;
2352       }
2353
2354       for (unsigned Val : NonNull->args()) {
2355         if (Val >= Args.size())
2356           continue;
2357         if (NonNullArgs.empty())
2358           NonNullArgs.resize(Args.size());
2359         NonNullArgs.set(Val);
2360       }
2361     }
2362   }
2363
2364   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2365     // Handle the nonnull attribute on the parameters of the
2366     // function/method.
2367     ArrayRef<ParmVarDecl*> parms;
2368     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2369       parms = FD->parameters();
2370     else
2371       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2372     
2373     unsigned ParamIndex = 0;
2374     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2375          I != E; ++I, ++ParamIndex) {
2376       const ParmVarDecl *PVD = *I;
2377       if (PVD->hasAttr<NonNullAttr>() || 
2378           isNonNullType(S.Context, PVD->getType())) {
2379         if (NonNullArgs.empty())
2380           NonNullArgs.resize(Args.size());
2381
2382         NonNullArgs.set(ParamIndex);
2383       }
2384     }
2385   } else {
2386     // If we have a non-function, non-method declaration but no
2387     // function prototype, try to dig out the function prototype.
2388     if (!Proto) {
2389       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2390         QualType type = VD->getType().getNonReferenceType();
2391         if (auto pointerType = type->getAs<PointerType>())
2392           type = pointerType->getPointeeType();
2393         else if (auto blockType = type->getAs<BlockPointerType>())
2394           type = blockType->getPointeeType();
2395         // FIXME: data member pointers?
2396
2397         // Dig out the function prototype, if there is one.
2398         Proto = type->getAs<FunctionProtoType>();
2399       } 
2400     }
2401
2402     // Fill in non-null argument information from the nullability
2403     // information on the parameter types (if we have them).
2404     if (Proto) {
2405       unsigned Index = 0;
2406       for (auto paramType : Proto->getParamTypes()) {
2407         if (isNonNullType(S.Context, paramType)) {
2408           if (NonNullArgs.empty())
2409             NonNullArgs.resize(Args.size());
2410           
2411           NonNullArgs.set(Index);
2412         }
2413         
2414         ++Index;
2415       }
2416     }
2417   }
2418
2419   // Check for non-null arguments.
2420   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 
2421        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2422     if (NonNullArgs[ArgIndex])
2423       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2424   }
2425 }
2426
2427 /// Handles the checks for format strings, non-POD arguments to vararg
2428 /// functions, and NULL arguments passed to non-NULL parameters.
2429 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2430                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2431                      SourceLocation Loc, SourceRange Range,
2432                      VariadicCallType CallType) {
2433   // FIXME: We should check as much as we can in the template definition.
2434   if (CurContext->isDependentContext())
2435     return;
2436
2437   // Printf and scanf checking.
2438   llvm::SmallBitVector CheckedVarArgs;
2439   if (FDecl) {
2440     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2441       // Only create vector if there are format attributes.
2442       CheckedVarArgs.resize(Args.size());
2443
2444       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2445                            CheckedVarArgs);
2446     }
2447   }
2448
2449   // Refuse POD arguments that weren't caught by the format string
2450   // checks above.
2451   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2452   if (CallType != VariadicDoesNotApply &&
2453       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2454     unsigned NumParams = Proto ? Proto->getNumParams()
2455                        : FDecl && isa<FunctionDecl>(FDecl)
2456                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2457                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2458                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2459                        : 0;
2460
2461     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2462       // Args[ArgIdx] can be null in malformed code.
2463       if (const Expr *Arg = Args[ArgIdx]) {
2464         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2465           checkVariadicArgument(Arg, CallType);
2466       }
2467     }
2468   }
2469
2470   if (FDecl || Proto) {
2471     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2472
2473     // Type safety checking.
2474     if (FDecl) {
2475       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2476         CheckArgumentWithTypeTag(I, Args.data());
2477     }
2478   }
2479 }
2480
2481 /// CheckConstructorCall - Check a constructor call for correctness and safety
2482 /// properties not enforced by the C type system.
2483 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2484                                 ArrayRef<const Expr *> Args,
2485                                 const FunctionProtoType *Proto,
2486                                 SourceLocation Loc) {
2487   VariadicCallType CallType =
2488     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2489   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(), 
2490             CallType);
2491 }
2492
2493 /// CheckFunctionCall - Check a direct function call for various correctness
2494 /// and safety properties not strictly enforced by the C type system.
2495 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2496                              const FunctionProtoType *Proto) {
2497   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2498                               isa<CXXMethodDecl>(FDecl);
2499   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2500                           IsMemberOperatorCall;
2501   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2502                                                   TheCall->getCallee());
2503   Expr** Args = TheCall->getArgs();
2504   unsigned NumArgs = TheCall->getNumArgs();
2505   if (IsMemberOperatorCall) {
2506     // If this is a call to a member operator, hide the first argument
2507     // from checkCall.
2508     // FIXME: Our choice of AST representation here is less than ideal.
2509     ++Args;
2510     --NumArgs;
2511   }
2512   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs), 
2513             IsMemberFunction, TheCall->getRParenLoc(),
2514             TheCall->getCallee()->getSourceRange(), CallType);
2515
2516   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2517   // None of the checks below are needed for functions that don't have
2518   // simple names (e.g., C++ conversion functions).
2519   if (!FnInfo)
2520     return false;
2521
2522   CheckAbsoluteValueFunction(TheCall, FDecl);
2523   CheckMaxUnsignedZero(TheCall, FDecl);
2524
2525   if (getLangOpts().ObjC1)
2526     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2527
2528   unsigned CMId = FDecl->getMemoryFunctionKind();
2529   if (CMId == 0)
2530     return false;
2531
2532   // Handle memory setting and copying functions.
2533   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2534     CheckStrlcpycatArguments(TheCall, FnInfo);
2535   else if (CMId == Builtin::BIstrncat)
2536     CheckStrncatArguments(TheCall, FnInfo);
2537   else
2538     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2539
2540   return false;
2541 }
2542
2543 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 
2544                                ArrayRef<const Expr *> Args) {
2545   VariadicCallType CallType =
2546       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2547
2548   checkCall(Method, nullptr, Args,
2549             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 
2550             CallType);
2551
2552   return false;
2553 }
2554
2555 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2556                             const FunctionProtoType *Proto) {
2557   QualType Ty;
2558   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2559     Ty = V->getType().getNonReferenceType();
2560   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2561     Ty = F->getType().getNonReferenceType();
2562   else
2563     return false;
2564
2565   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2566       !Ty->isFunctionProtoType())
2567     return false;
2568
2569   VariadicCallType CallType;
2570   if (!Proto || !Proto->isVariadic()) {
2571     CallType = VariadicDoesNotApply;
2572   } else if (Ty->isBlockPointerType()) {
2573     CallType = VariadicBlock;
2574   } else { // Ty->isFunctionPointerType()
2575     CallType = VariadicFunction;
2576   }
2577
2578   checkCall(NDecl, Proto,
2579             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2580             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2581             TheCall->getCallee()->getSourceRange(), CallType);
2582
2583   return false;
2584 }
2585
2586 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2587 /// such as function pointers returned from functions.
2588 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2589   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2590                                                   TheCall->getCallee());
2591   checkCall(/*FDecl=*/nullptr, Proto,
2592             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2593             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2594             TheCall->getCallee()->getSourceRange(), CallType);
2595
2596   return false;
2597 }
2598
2599 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2600   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2601     return false;
2602
2603   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2604   switch (Op) {
2605   case AtomicExpr::AO__c11_atomic_init:
2606     llvm_unreachable("There is no ordering argument for an init");
2607
2608   case AtomicExpr::AO__c11_atomic_load:
2609   case AtomicExpr::AO__atomic_load_n:
2610   case AtomicExpr::AO__atomic_load:
2611     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2612            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2613
2614   case AtomicExpr::AO__c11_atomic_store:
2615   case AtomicExpr::AO__atomic_store:
2616   case AtomicExpr::AO__atomic_store_n:
2617     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2618            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2619            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2620
2621   default:
2622     return true;
2623   }
2624 }
2625
2626 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2627                                          AtomicExpr::AtomicOp Op) {
2628   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2629   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2630
2631   // All these operations take one of the following forms:
2632   enum {
2633     // C    __c11_atomic_init(A *, C)
2634     Init,
2635     // C    __c11_atomic_load(A *, int)
2636     Load,
2637     // void __atomic_load(A *, CP, int)
2638     LoadCopy,
2639     // void __atomic_store(A *, CP, int)
2640     Copy,
2641     // C    __c11_atomic_add(A *, M, int)
2642     Arithmetic,
2643     // C    __atomic_exchange_n(A *, CP, int)
2644     Xchg,
2645     // void __atomic_exchange(A *, C *, CP, int)
2646     GNUXchg,
2647     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2648     C11CmpXchg,
2649     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2650     GNUCmpXchg
2651   } Form = Init;
2652   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2653   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2654   // where:
2655   //   C is an appropriate type,
2656   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2657   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2658   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2659   //   the int parameters are for orderings.
2660
2661   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2662                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2663                         AtomicExpr::AO__atomic_load,
2664                 "need to update code for modified C11 atomics");
2665   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2666                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2667   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2668              Op == AtomicExpr::AO__atomic_store_n ||
2669              Op == AtomicExpr::AO__atomic_exchange_n ||
2670              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2671   bool IsAddSub = false;
2672
2673   switch (Op) {
2674   case AtomicExpr::AO__c11_atomic_init:
2675     Form = Init;
2676     break;
2677
2678   case AtomicExpr::AO__c11_atomic_load:
2679   case AtomicExpr::AO__atomic_load_n:
2680     Form = Load;
2681     break;
2682
2683   case AtomicExpr::AO__atomic_load:
2684     Form = LoadCopy;
2685     break;
2686
2687   case AtomicExpr::AO__c11_atomic_store:
2688   case AtomicExpr::AO__atomic_store:
2689   case AtomicExpr::AO__atomic_store_n:
2690     Form = Copy;
2691     break;
2692
2693   case AtomicExpr::AO__c11_atomic_fetch_add:
2694   case AtomicExpr::AO__c11_atomic_fetch_sub:
2695   case AtomicExpr::AO__atomic_fetch_add:
2696   case AtomicExpr::AO__atomic_fetch_sub:
2697   case AtomicExpr::AO__atomic_add_fetch:
2698   case AtomicExpr::AO__atomic_sub_fetch:
2699     IsAddSub = true;
2700     // Fall through.
2701   case AtomicExpr::AO__c11_atomic_fetch_and:
2702   case AtomicExpr::AO__c11_atomic_fetch_or:
2703   case AtomicExpr::AO__c11_atomic_fetch_xor:
2704   case AtomicExpr::AO__atomic_fetch_and:
2705   case AtomicExpr::AO__atomic_fetch_or:
2706   case AtomicExpr::AO__atomic_fetch_xor:
2707   case AtomicExpr::AO__atomic_fetch_nand:
2708   case AtomicExpr::AO__atomic_and_fetch:
2709   case AtomicExpr::AO__atomic_or_fetch:
2710   case AtomicExpr::AO__atomic_xor_fetch:
2711   case AtomicExpr::AO__atomic_nand_fetch:
2712     Form = Arithmetic;
2713     break;
2714
2715   case AtomicExpr::AO__c11_atomic_exchange:
2716   case AtomicExpr::AO__atomic_exchange_n:
2717     Form = Xchg;
2718     break;
2719
2720   case AtomicExpr::AO__atomic_exchange:
2721     Form = GNUXchg;
2722     break;
2723
2724   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2725   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2726     Form = C11CmpXchg;
2727     break;
2728
2729   case AtomicExpr::AO__atomic_compare_exchange:
2730   case AtomicExpr::AO__atomic_compare_exchange_n:
2731     Form = GNUCmpXchg;
2732     break;
2733   }
2734
2735   // Check we have the right number of arguments.
2736   if (TheCall->getNumArgs() < NumArgs[Form]) {
2737     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2738       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2739       << TheCall->getCallee()->getSourceRange();
2740     return ExprError();
2741   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2742     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2743          diag::err_typecheck_call_too_many_args)
2744       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2745       << TheCall->getCallee()->getSourceRange();
2746     return ExprError();
2747   }
2748
2749   // Inspect the first argument of the atomic operation.
2750   Expr *Ptr = TheCall->getArg(0);
2751   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2752   if (ConvertedPtr.isInvalid())
2753     return ExprError();
2754
2755   Ptr = ConvertedPtr.get();
2756   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2757   if (!pointerType) {
2758     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2759       << Ptr->getType() << Ptr->getSourceRange();
2760     return ExprError();
2761   }
2762
2763   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2764   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2765   QualType ValType = AtomTy; // 'C'
2766   if (IsC11) {
2767     if (!AtomTy->isAtomicType()) {
2768       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2769         << Ptr->getType() << Ptr->getSourceRange();
2770       return ExprError();
2771     }
2772     if (AtomTy.isConstQualified()) {
2773       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2774         << Ptr->getType() << Ptr->getSourceRange();
2775       return ExprError();
2776     }
2777     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2778   } else if (Form != Load && Form != LoadCopy) {
2779     if (ValType.isConstQualified()) {
2780       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2781         << Ptr->getType() << Ptr->getSourceRange();
2782       return ExprError();
2783     }
2784   }
2785
2786   // For an arithmetic operation, the implied arithmetic must be well-formed.
2787   if (Form == Arithmetic) {
2788     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2789     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2790       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2791         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2792       return ExprError();
2793     }
2794     if (!IsAddSub && !ValType->isIntegerType()) {
2795       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2796         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2797       return ExprError();
2798     }
2799     if (IsC11 && ValType->isPointerType() &&
2800         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2801                             diag::err_incomplete_type)) {
2802       return ExprError();
2803     }
2804   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2805     // For __atomic_*_n operations, the value type must be a scalar integral or
2806     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2807     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2808       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2809     return ExprError();
2810   }
2811
2812   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2813       !AtomTy->isScalarType()) {
2814     // For GNU atomics, require a trivially-copyable type. This is not part of
2815     // the GNU atomics specification, but we enforce it for sanity.
2816     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2817       << Ptr->getType() << Ptr->getSourceRange();
2818     return ExprError();
2819   }
2820
2821   switch (ValType.getObjCLifetime()) {
2822   case Qualifiers::OCL_None:
2823   case Qualifiers::OCL_ExplicitNone:
2824     // okay
2825     break;
2826
2827   case Qualifiers::OCL_Weak:
2828   case Qualifiers::OCL_Strong:
2829   case Qualifiers::OCL_Autoreleasing:
2830     // FIXME: Can this happen? By this point, ValType should be known
2831     // to be trivially copyable.
2832     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2833       << ValType << Ptr->getSourceRange();
2834     return ExprError();
2835   }
2836
2837   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2838   // volatile-ness of the pointee-type inject itself into the result or the
2839   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2840   ValType.removeLocalVolatile();
2841   ValType.removeLocalConst();
2842   QualType ResultType = ValType;
2843   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2844     ResultType = Context.VoidTy;
2845   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2846     ResultType = Context.BoolTy;
2847
2848   // The type of a parameter passed 'by value'. In the GNU atomics, such
2849   // arguments are actually passed as pointers.
2850   QualType ByValType = ValType; // 'CP'
2851   if (!IsC11 && !IsN)
2852     ByValType = Ptr->getType();
2853
2854   // The first argument --- the pointer --- has a fixed type; we
2855   // deduce the types of the rest of the arguments accordingly.  Walk
2856   // the remaining arguments, converting them to the deduced value type.
2857   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2858     QualType Ty;
2859     if (i < NumVals[Form] + 1) {
2860       switch (i) {
2861       case 1:
2862         // The second argument is the non-atomic operand. For arithmetic, this
2863         // is always passed by value, and for a compare_exchange it is always
2864         // passed by address. For the rest, GNU uses by-address and C11 uses
2865         // by-value.
2866         assert(Form != Load);
2867         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2868           Ty = ValType;
2869         else if (Form == Copy || Form == Xchg)
2870           Ty = ByValType;
2871         else if (Form == Arithmetic)
2872           Ty = Context.getPointerDiffType();
2873         else {
2874           Expr *ValArg = TheCall->getArg(i);
2875           // Treat this argument as _Nonnull as we want to show a warning if
2876           // NULL is passed into it.
2877           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
2878           unsigned AS = 0;
2879           // Keep address space of non-atomic pointer type.
2880           if (const PointerType *PtrTy =
2881                   ValArg->getType()->getAs<PointerType>()) {
2882             AS = PtrTy->getPointeeType().getAddressSpace();
2883           }
2884           Ty = Context.getPointerType(
2885               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2886         }
2887         break;
2888       case 2:
2889         // The third argument to compare_exchange / GNU exchange is a
2890         // (pointer to a) desired value.
2891         Ty = ByValType;
2892         break;
2893       case 3:
2894         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2895         Ty = Context.BoolTy;
2896         break;
2897       }
2898     } else {
2899       // The order(s) are always converted to int.
2900       Ty = Context.IntTy;
2901     }
2902
2903     InitializedEntity Entity =
2904         InitializedEntity::InitializeParameter(Context, Ty, false);
2905     ExprResult Arg = TheCall->getArg(i);
2906     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2907     if (Arg.isInvalid())
2908       return true;
2909     TheCall->setArg(i, Arg.get());
2910   }
2911
2912   // Permute the arguments into a 'consistent' order.
2913   SmallVector<Expr*, 5> SubExprs;
2914   SubExprs.push_back(Ptr);
2915   switch (Form) {
2916   case Init:
2917     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2918     SubExprs.push_back(TheCall->getArg(1)); // Val1
2919     break;
2920   case Load:
2921     SubExprs.push_back(TheCall->getArg(1)); // Order
2922     break;
2923   case LoadCopy:
2924   case Copy:
2925   case Arithmetic:
2926   case Xchg:
2927     SubExprs.push_back(TheCall->getArg(2)); // Order
2928     SubExprs.push_back(TheCall->getArg(1)); // Val1
2929     break;
2930   case GNUXchg:
2931     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2932     SubExprs.push_back(TheCall->getArg(3)); // Order
2933     SubExprs.push_back(TheCall->getArg(1)); // Val1
2934     SubExprs.push_back(TheCall->getArg(2)); // Val2
2935     break;
2936   case C11CmpXchg:
2937     SubExprs.push_back(TheCall->getArg(3)); // Order
2938     SubExprs.push_back(TheCall->getArg(1)); // Val1
2939     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2940     SubExprs.push_back(TheCall->getArg(2)); // Val2
2941     break;
2942   case GNUCmpXchg:
2943     SubExprs.push_back(TheCall->getArg(4)); // Order
2944     SubExprs.push_back(TheCall->getArg(1)); // Val1
2945     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2946     SubExprs.push_back(TheCall->getArg(2)); // Val2
2947     SubExprs.push_back(TheCall->getArg(3)); // Weak
2948     break;
2949   }
2950
2951   if (SubExprs.size() >= 2 && Form != Init) {
2952     llvm::APSInt Result(32);
2953     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2954         !isValidOrderingForOp(Result.getSExtValue(), Op))
2955       Diag(SubExprs[1]->getLocStart(),
2956            diag::warn_atomic_op_has_invalid_memory_order)
2957           << SubExprs[1]->getSourceRange();
2958   }
2959
2960   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2961                                             SubExprs, ResultType, Op,
2962                                             TheCall->getRParenLoc());
2963   
2964   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2965        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2966       Context.AtomicUsesUnsupportedLibcall(AE))
2967     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2968     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2969
2970   return AE;
2971 }
2972
2973 /// checkBuiltinArgument - Given a call to a builtin function, perform
2974 /// normal type-checking on the given argument, updating the call in
2975 /// place.  This is useful when a builtin function requires custom
2976 /// type-checking for some of its arguments but not necessarily all of
2977 /// them.
2978 ///
2979 /// Returns true on error.
2980 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2981   FunctionDecl *Fn = E->getDirectCallee();
2982   assert(Fn && "builtin call without direct callee!");
2983
2984   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2985   InitializedEntity Entity =
2986     InitializedEntity::InitializeParameter(S.Context, Param);
2987
2988   ExprResult Arg = E->getArg(0);
2989   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2990   if (Arg.isInvalid())
2991     return true;
2992
2993   E->setArg(ArgIndex, Arg.get());
2994   return false;
2995 }
2996
2997 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2998 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2999 /// type of its first argument.  The main ActOnCallExpr routines have already
3000 /// promoted the types of arguments because all of these calls are prototyped as
3001 /// void(...).
3002 ///
3003 /// This function goes through and does final semantic checking for these
3004 /// builtins,
3005 ExprResult
3006 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3007   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3008   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3009   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3010
3011   // Ensure that we have at least one argument to do type inference from.
3012   if (TheCall->getNumArgs() < 1) {
3013     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3014       << 0 << 1 << TheCall->getNumArgs()
3015       << TheCall->getCallee()->getSourceRange();
3016     return ExprError();
3017   }
3018
3019   // Inspect the first argument of the atomic builtin.  This should always be
3020   // a pointer type, whose element is an integral scalar or pointer type.
3021   // Because it is a pointer type, we don't have to worry about any implicit
3022   // casts here.
3023   // FIXME: We don't allow floating point scalars as input.
3024   Expr *FirstArg = TheCall->getArg(0);
3025   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3026   if (FirstArgResult.isInvalid())
3027     return ExprError();
3028   FirstArg = FirstArgResult.get();
3029   TheCall->setArg(0, FirstArg);
3030
3031   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3032   if (!pointerType) {
3033     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3034       << FirstArg->getType() << FirstArg->getSourceRange();
3035     return ExprError();
3036   }
3037
3038   QualType ValType = pointerType->getPointeeType();
3039   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3040       !ValType->isBlockPointerType()) {
3041     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3042       << FirstArg->getType() << FirstArg->getSourceRange();
3043     return ExprError();
3044   }
3045
3046   switch (ValType.getObjCLifetime()) {
3047   case Qualifiers::OCL_None:
3048   case Qualifiers::OCL_ExplicitNone:
3049     // okay
3050     break;
3051
3052   case Qualifiers::OCL_Weak:
3053   case Qualifiers::OCL_Strong:
3054   case Qualifiers::OCL_Autoreleasing:
3055     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3056       << ValType << FirstArg->getSourceRange();
3057     return ExprError();
3058   }
3059
3060   // Strip any qualifiers off ValType.
3061   ValType = ValType.getUnqualifiedType();
3062
3063   // The majority of builtins return a value, but a few have special return
3064   // types, so allow them to override appropriately below.
3065   QualType ResultType = ValType;
3066
3067   // We need to figure out which concrete builtin this maps onto.  For example,
3068   // __sync_fetch_and_add with a 2 byte object turns into
3069   // __sync_fetch_and_add_2.
3070 #define BUILTIN_ROW(x) \
3071   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3072     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3073
3074   static const unsigned BuiltinIndices[][5] = {
3075     BUILTIN_ROW(__sync_fetch_and_add),
3076     BUILTIN_ROW(__sync_fetch_and_sub),
3077     BUILTIN_ROW(__sync_fetch_and_or),
3078     BUILTIN_ROW(__sync_fetch_and_and),
3079     BUILTIN_ROW(__sync_fetch_and_xor),
3080     BUILTIN_ROW(__sync_fetch_and_nand),
3081
3082     BUILTIN_ROW(__sync_add_and_fetch),
3083     BUILTIN_ROW(__sync_sub_and_fetch),
3084     BUILTIN_ROW(__sync_and_and_fetch),
3085     BUILTIN_ROW(__sync_or_and_fetch),
3086     BUILTIN_ROW(__sync_xor_and_fetch),
3087     BUILTIN_ROW(__sync_nand_and_fetch),
3088
3089     BUILTIN_ROW(__sync_val_compare_and_swap),
3090     BUILTIN_ROW(__sync_bool_compare_and_swap),
3091     BUILTIN_ROW(__sync_lock_test_and_set),
3092     BUILTIN_ROW(__sync_lock_release),
3093     BUILTIN_ROW(__sync_swap)
3094   };
3095 #undef BUILTIN_ROW
3096
3097   // Determine the index of the size.
3098   unsigned SizeIndex;
3099   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3100   case 1: SizeIndex = 0; break;
3101   case 2: SizeIndex = 1; break;
3102   case 4: SizeIndex = 2; break;
3103   case 8: SizeIndex = 3; break;
3104   case 16: SizeIndex = 4; break;
3105   default:
3106     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3107       << FirstArg->getType() << FirstArg->getSourceRange();
3108     return ExprError();
3109   }
3110
3111   // Each of these builtins has one pointer argument, followed by some number of
3112   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3113   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3114   // as the number of fixed args.
3115   unsigned BuiltinID = FDecl->getBuiltinID();
3116   unsigned BuiltinIndex, NumFixed = 1;
3117   bool WarnAboutSemanticsChange = false;
3118   switch (BuiltinID) {
3119   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3120   case Builtin::BI__sync_fetch_and_add: 
3121   case Builtin::BI__sync_fetch_and_add_1:
3122   case Builtin::BI__sync_fetch_and_add_2:
3123   case Builtin::BI__sync_fetch_and_add_4:
3124   case Builtin::BI__sync_fetch_and_add_8:
3125   case Builtin::BI__sync_fetch_and_add_16:
3126     BuiltinIndex = 0; 
3127     break;
3128       
3129   case Builtin::BI__sync_fetch_and_sub: 
3130   case Builtin::BI__sync_fetch_and_sub_1:
3131   case Builtin::BI__sync_fetch_and_sub_2:
3132   case Builtin::BI__sync_fetch_and_sub_4:
3133   case Builtin::BI__sync_fetch_and_sub_8:
3134   case Builtin::BI__sync_fetch_and_sub_16:
3135     BuiltinIndex = 1; 
3136     break;
3137       
3138   case Builtin::BI__sync_fetch_and_or:  
3139   case Builtin::BI__sync_fetch_and_or_1:
3140   case Builtin::BI__sync_fetch_and_or_2:
3141   case Builtin::BI__sync_fetch_and_or_4:
3142   case Builtin::BI__sync_fetch_and_or_8:
3143   case Builtin::BI__sync_fetch_and_or_16:
3144     BuiltinIndex = 2; 
3145     break;
3146       
3147   case Builtin::BI__sync_fetch_and_and: 
3148   case Builtin::BI__sync_fetch_and_and_1:
3149   case Builtin::BI__sync_fetch_and_and_2:
3150   case Builtin::BI__sync_fetch_and_and_4:
3151   case Builtin::BI__sync_fetch_and_and_8:
3152   case Builtin::BI__sync_fetch_and_and_16:
3153     BuiltinIndex = 3; 
3154     break;
3155
3156   case Builtin::BI__sync_fetch_and_xor: 
3157   case Builtin::BI__sync_fetch_and_xor_1:
3158   case Builtin::BI__sync_fetch_and_xor_2:
3159   case Builtin::BI__sync_fetch_and_xor_4:
3160   case Builtin::BI__sync_fetch_and_xor_8:
3161   case Builtin::BI__sync_fetch_and_xor_16:
3162     BuiltinIndex = 4; 
3163     break;
3164
3165   case Builtin::BI__sync_fetch_and_nand: 
3166   case Builtin::BI__sync_fetch_and_nand_1:
3167   case Builtin::BI__sync_fetch_and_nand_2:
3168   case Builtin::BI__sync_fetch_and_nand_4:
3169   case Builtin::BI__sync_fetch_and_nand_8:
3170   case Builtin::BI__sync_fetch_and_nand_16:
3171     BuiltinIndex = 5;
3172     WarnAboutSemanticsChange = true;
3173     break;
3174
3175   case Builtin::BI__sync_add_and_fetch: 
3176   case Builtin::BI__sync_add_and_fetch_1:
3177   case Builtin::BI__sync_add_and_fetch_2:
3178   case Builtin::BI__sync_add_and_fetch_4:
3179   case Builtin::BI__sync_add_and_fetch_8:
3180   case Builtin::BI__sync_add_and_fetch_16:
3181     BuiltinIndex = 6; 
3182     break;
3183       
3184   case Builtin::BI__sync_sub_and_fetch: 
3185   case Builtin::BI__sync_sub_and_fetch_1:
3186   case Builtin::BI__sync_sub_and_fetch_2:
3187   case Builtin::BI__sync_sub_and_fetch_4:
3188   case Builtin::BI__sync_sub_and_fetch_8:
3189   case Builtin::BI__sync_sub_and_fetch_16:
3190     BuiltinIndex = 7; 
3191     break;
3192       
3193   case Builtin::BI__sync_and_and_fetch: 
3194   case Builtin::BI__sync_and_and_fetch_1:
3195   case Builtin::BI__sync_and_and_fetch_2:
3196   case Builtin::BI__sync_and_and_fetch_4:
3197   case Builtin::BI__sync_and_and_fetch_8:
3198   case Builtin::BI__sync_and_and_fetch_16:
3199     BuiltinIndex = 8; 
3200     break;
3201       
3202   case Builtin::BI__sync_or_and_fetch:  
3203   case Builtin::BI__sync_or_and_fetch_1:
3204   case Builtin::BI__sync_or_and_fetch_2:
3205   case Builtin::BI__sync_or_and_fetch_4:
3206   case Builtin::BI__sync_or_and_fetch_8:
3207   case Builtin::BI__sync_or_and_fetch_16:
3208     BuiltinIndex = 9; 
3209     break;
3210       
3211   case Builtin::BI__sync_xor_and_fetch: 
3212   case Builtin::BI__sync_xor_and_fetch_1:
3213   case Builtin::BI__sync_xor_and_fetch_2:
3214   case Builtin::BI__sync_xor_and_fetch_4:
3215   case Builtin::BI__sync_xor_and_fetch_8:
3216   case Builtin::BI__sync_xor_and_fetch_16:
3217     BuiltinIndex = 10;
3218     break;
3219
3220   case Builtin::BI__sync_nand_and_fetch: 
3221   case Builtin::BI__sync_nand_and_fetch_1:
3222   case Builtin::BI__sync_nand_and_fetch_2:
3223   case Builtin::BI__sync_nand_and_fetch_4:
3224   case Builtin::BI__sync_nand_and_fetch_8:
3225   case Builtin::BI__sync_nand_and_fetch_16:
3226     BuiltinIndex = 11;
3227     WarnAboutSemanticsChange = true;
3228     break;
3229
3230   case Builtin::BI__sync_val_compare_and_swap:
3231   case Builtin::BI__sync_val_compare_and_swap_1:
3232   case Builtin::BI__sync_val_compare_and_swap_2:
3233   case Builtin::BI__sync_val_compare_and_swap_4:
3234   case Builtin::BI__sync_val_compare_and_swap_8:
3235   case Builtin::BI__sync_val_compare_and_swap_16:
3236     BuiltinIndex = 12;
3237     NumFixed = 2;
3238     break;
3239       
3240   case Builtin::BI__sync_bool_compare_and_swap:
3241   case Builtin::BI__sync_bool_compare_and_swap_1:
3242   case Builtin::BI__sync_bool_compare_and_swap_2:
3243   case Builtin::BI__sync_bool_compare_and_swap_4:
3244   case Builtin::BI__sync_bool_compare_and_swap_8:
3245   case Builtin::BI__sync_bool_compare_and_swap_16:
3246     BuiltinIndex = 13;
3247     NumFixed = 2;
3248     ResultType = Context.BoolTy;
3249     break;
3250       
3251   case Builtin::BI__sync_lock_test_and_set: 
3252   case Builtin::BI__sync_lock_test_and_set_1:
3253   case Builtin::BI__sync_lock_test_and_set_2:
3254   case Builtin::BI__sync_lock_test_and_set_4:
3255   case Builtin::BI__sync_lock_test_and_set_8:
3256   case Builtin::BI__sync_lock_test_and_set_16:
3257     BuiltinIndex = 14; 
3258     break;
3259       
3260   case Builtin::BI__sync_lock_release:
3261   case Builtin::BI__sync_lock_release_1:
3262   case Builtin::BI__sync_lock_release_2:
3263   case Builtin::BI__sync_lock_release_4:
3264   case Builtin::BI__sync_lock_release_8:
3265   case Builtin::BI__sync_lock_release_16:
3266     BuiltinIndex = 15;
3267     NumFixed = 0;
3268     ResultType = Context.VoidTy;
3269     break;
3270       
3271   case Builtin::BI__sync_swap: 
3272   case Builtin::BI__sync_swap_1:
3273   case Builtin::BI__sync_swap_2:
3274   case Builtin::BI__sync_swap_4:
3275   case Builtin::BI__sync_swap_8:
3276   case Builtin::BI__sync_swap_16:
3277     BuiltinIndex = 16; 
3278     break;
3279   }
3280
3281   // Now that we know how many fixed arguments we expect, first check that we
3282   // have at least that many.
3283   if (TheCall->getNumArgs() < 1+NumFixed) {
3284     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3285       << 0 << 1+NumFixed << TheCall->getNumArgs()
3286       << TheCall->getCallee()->getSourceRange();
3287     return ExprError();
3288   }
3289
3290   if (WarnAboutSemanticsChange) {
3291     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3292       << TheCall->getCallee()->getSourceRange();
3293   }
3294
3295   // Get the decl for the concrete builtin from this, we can tell what the
3296   // concrete integer type we should convert to is.
3297   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3298   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3299   FunctionDecl *NewBuiltinDecl;
3300   if (NewBuiltinID == BuiltinID)
3301     NewBuiltinDecl = FDecl;
3302   else {
3303     // Perform builtin lookup to avoid redeclaring it.
3304     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3305     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3306     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3307     assert(Res.getFoundDecl());
3308     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3309     if (!NewBuiltinDecl)
3310       return ExprError();
3311   }
3312
3313   // The first argument --- the pointer --- has a fixed type; we
3314   // deduce the types of the rest of the arguments accordingly.  Walk
3315   // the remaining arguments, converting them to the deduced value type.
3316   for (unsigned i = 0; i != NumFixed; ++i) {
3317     ExprResult Arg = TheCall->getArg(i+1);
3318
3319     // GCC does an implicit conversion to the pointer or integer ValType.  This
3320     // can fail in some cases (1i -> int**), check for this error case now.
3321     // Initialize the argument.
3322     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3323                                                    ValType, /*consume*/ false);
3324     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3325     if (Arg.isInvalid())
3326       return ExprError();
3327
3328     // Okay, we have something that *can* be converted to the right type.  Check
3329     // to see if there is a potentially weird extension going on here.  This can
3330     // happen when you do an atomic operation on something like an char* and
3331     // pass in 42.  The 42 gets converted to char.  This is even more strange
3332     // for things like 45.123 -> char, etc.
3333     // FIXME: Do this check.
3334     TheCall->setArg(i+1, Arg.get());
3335   }
3336
3337   ASTContext& Context = this->getASTContext();
3338
3339   // Create a new DeclRefExpr to refer to the new decl.
3340   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3341       Context,
3342       DRE->getQualifierLoc(),
3343       SourceLocation(),
3344       NewBuiltinDecl,
3345       /*enclosing*/ false,
3346       DRE->getLocation(),
3347       Context.BuiltinFnTy,
3348       DRE->getValueKind());
3349
3350   // Set the callee in the CallExpr.
3351   // FIXME: This loses syntactic information.
3352   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3353   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3354                                               CK_BuiltinFnToFnPtr);
3355   TheCall->setCallee(PromotedCall.get());
3356
3357   // Change the result type of the call to match the original value type. This
3358   // is arbitrary, but the codegen for these builtins ins design to handle it
3359   // gracefully.
3360   TheCall->setType(ResultType);
3361
3362   return TheCallResult;
3363 }
3364
3365 /// SemaBuiltinNontemporalOverloaded - We have a call to
3366 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3367 /// overloaded function based on the pointer type of its last argument.
3368 ///
3369 /// This function goes through and does final semantic checking for these
3370 /// builtins.
3371 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3372   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3373   DeclRefExpr *DRE =
3374       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3375   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3376   unsigned BuiltinID = FDecl->getBuiltinID();
3377   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3378           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3379          "Unexpected nontemporal load/store builtin!");
3380   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3381   unsigned numArgs = isStore ? 2 : 1;
3382
3383   // Ensure that we have the proper number of arguments.
3384   if (checkArgCount(*this, TheCall, numArgs))
3385     return ExprError();
3386
3387   // Inspect the last argument of the nontemporal builtin.  This should always
3388   // be a pointer type, from which we imply the type of the memory access.
3389   // Because it is a pointer type, we don't have to worry about any implicit
3390   // casts here.
3391   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3392   ExprResult PointerArgResult =
3393       DefaultFunctionArrayLvalueConversion(PointerArg);
3394
3395   if (PointerArgResult.isInvalid())
3396     return ExprError();
3397   PointerArg = PointerArgResult.get();
3398   TheCall->setArg(numArgs - 1, PointerArg);
3399
3400   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3401   if (!pointerType) {
3402     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3403         << PointerArg->getType() << PointerArg->getSourceRange();
3404     return ExprError();
3405   }
3406
3407   QualType ValType = pointerType->getPointeeType();
3408
3409   // Strip any qualifiers off ValType.
3410   ValType = ValType.getUnqualifiedType();
3411   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3412       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3413       !ValType->isVectorType()) {
3414     Diag(DRE->getLocStart(),
3415          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3416         << PointerArg->getType() << PointerArg->getSourceRange();
3417     return ExprError();
3418   }
3419
3420   if (!isStore) {
3421     TheCall->setType(ValType);
3422     return TheCallResult;
3423   }
3424
3425   ExprResult ValArg = TheCall->getArg(0);
3426   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3427       Context, ValType, /*consume*/ false);
3428   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3429   if (ValArg.isInvalid())
3430     return ExprError();
3431
3432   TheCall->setArg(0, ValArg.get());
3433   TheCall->setType(Context.VoidTy);
3434   return TheCallResult;
3435 }
3436
3437 /// CheckObjCString - Checks that the argument to the builtin
3438 /// CFString constructor is correct
3439 /// Note: It might also make sense to do the UTF-16 conversion here (would
3440 /// simplify the backend).
3441 bool Sema::CheckObjCString(Expr *Arg) {
3442   Arg = Arg->IgnoreParenCasts();
3443   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3444
3445   if (!Literal || !Literal->isAscii()) {
3446     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3447       << Arg->getSourceRange();
3448     return true;
3449   }
3450
3451   if (Literal->containsNonAsciiOrNull()) {
3452     StringRef String = Literal->getString();
3453     unsigned NumBytes = String.size();
3454     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3455     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3456     llvm::UTF16 *ToPtr = &ToBuf[0];
3457
3458     llvm::ConversionResult Result =
3459         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3460                                  ToPtr + NumBytes, llvm::strictConversion);
3461     // Check for conversion failure.
3462     if (Result != llvm::conversionOK)
3463       Diag(Arg->getLocStart(),
3464            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3465   }
3466   return false;
3467 }
3468
3469 /// CheckObjCString - Checks that the format string argument to the os_log()
3470 /// and os_trace() functions is correct, and converts it to const char *.
3471 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3472   Arg = Arg->IgnoreParenCasts();
3473   auto *Literal = dyn_cast<StringLiteral>(Arg);
3474   if (!Literal) {
3475     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3476       Literal = ObjcLiteral->getString();
3477     }
3478   }
3479
3480   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3481     return ExprError(
3482         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3483         << Arg->getSourceRange());
3484   }
3485
3486   ExprResult Result(Literal);
3487   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3488   InitializedEntity Entity =
3489       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3490   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3491   return Result;
3492 }
3493
3494 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3495 /// for validity.  Emit an error and return true on failure; return false
3496 /// on success.
3497 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3498   Expr *Fn = TheCall->getCallee();
3499   if (TheCall->getNumArgs() > 2) {
3500     Diag(TheCall->getArg(2)->getLocStart(),
3501          diag::err_typecheck_call_too_many_args)
3502       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3503       << Fn->getSourceRange()
3504       << SourceRange(TheCall->getArg(2)->getLocStart(),
3505                      (*(TheCall->arg_end()-1))->getLocEnd());
3506     return true;
3507   }
3508
3509   if (TheCall->getNumArgs() < 2) {
3510     return Diag(TheCall->getLocEnd(),
3511       diag::err_typecheck_call_too_few_args_at_least)
3512       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3513   }
3514
3515   // Type-check the first argument normally.
3516   if (checkBuiltinArgument(*this, TheCall, 0))
3517     return true;
3518
3519   // Determine whether the current function is variadic or not.
3520   BlockScopeInfo *CurBlock = getCurBlock();
3521   bool isVariadic;
3522   if (CurBlock)
3523     isVariadic = CurBlock->TheDecl->isVariadic();
3524   else if (FunctionDecl *FD = getCurFunctionDecl())
3525     isVariadic = FD->isVariadic();
3526   else
3527     isVariadic = getCurMethodDecl()->isVariadic();
3528
3529   if (!isVariadic) {
3530     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3531     return true;
3532   }
3533
3534   // Verify that the second argument to the builtin is the last argument of the
3535   // current function or method.
3536   bool SecondArgIsLastNamedArgument = false;
3537   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3538
3539   // These are valid if SecondArgIsLastNamedArgument is false after the next
3540   // block.
3541   QualType Type;
3542   SourceLocation ParamLoc;
3543   bool IsCRegister = false;
3544
3545   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3546     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3547       // FIXME: This isn't correct for methods (results in bogus warning).
3548       // Get the last formal in the current function.
3549       const ParmVarDecl *LastArg;
3550       if (CurBlock)
3551         LastArg = CurBlock->TheDecl->parameters().back();
3552       else if (FunctionDecl *FD = getCurFunctionDecl())
3553         LastArg = FD->parameters().back();
3554       else
3555         LastArg = getCurMethodDecl()->parameters().back();
3556       SecondArgIsLastNamedArgument = PV == LastArg;
3557
3558       Type = PV->getType();
3559       ParamLoc = PV->getLocation();
3560       IsCRegister =
3561           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3562     }
3563   }
3564
3565   if (!SecondArgIsLastNamedArgument)
3566     Diag(TheCall->getArg(1)->getLocStart(),
3567          diag::warn_second_arg_of_va_start_not_last_named_param);
3568   else if (IsCRegister || Type->isReferenceType() ||
3569            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3570              // Promotable integers are UB, but enumerations need a bit of
3571              // extra checking to see what their promotable type actually is.
3572              if (!Type->isPromotableIntegerType())
3573                return false;
3574              if (!Type->isEnumeralType())
3575                return true;
3576              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3577              return !(ED &&
3578                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3579            }()) {
3580     unsigned Reason = 0;
3581     if (Type->isReferenceType())  Reason = 1;
3582     else if (IsCRegister)         Reason = 2;
3583     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3584     Diag(ParamLoc, diag::note_parameter_type) << Type;
3585   }
3586
3587   TheCall->setType(Context.VoidTy);
3588   return false;
3589 }
3590
3591 /// Check the arguments to '__builtin_va_start' for validity, and that
3592 /// it was called from a function of the native ABI.
3593 /// Emit an error and return true on failure; return false on success.
3594 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3595   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3596   // On x64 Windows, don't allow this in System V ABI functions.
3597   // (Yes, that means there's no corresponding way to support variadic
3598   // System V ABI functions on Windows.)
3599   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3600     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3601     clang::CallingConv CC = CC_C;
3602     if (const FunctionDecl *FD = getCurFunctionDecl())
3603       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3604     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3605         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3606       return Diag(TheCall->getCallee()->getLocStart(),
3607                   diag::err_va_start_used_in_wrong_abi_function)
3608              << (OS != llvm::Triple::Win32);
3609   }
3610   return SemaBuiltinVAStartImpl(TheCall);
3611 }
3612
3613 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3614 /// it was called from a Win64 ABI function.
3615 /// Emit an error and return true on failure; return false on success.
3616 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3617   // This only makes sense for x86-64.
3618   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3619   Expr *Callee = TheCall->getCallee();
3620   if (TT.getArch() != llvm::Triple::x86_64)
3621     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3622   // Don't allow this in System V ABI functions.
3623   clang::CallingConv CC = CC_C;
3624   if (const FunctionDecl *FD = getCurFunctionDecl())
3625     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3626   if (CC == CC_X86_64SysV ||
3627       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3628     return Diag(Callee->getLocStart(),
3629                 diag::err_ms_va_start_used_in_sysv_function);
3630   return SemaBuiltinVAStartImpl(TheCall);
3631 }
3632
3633 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3634   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3635   //                 const char *named_addr);
3636
3637   Expr *Func = Call->getCallee();
3638
3639   if (Call->getNumArgs() < 3)
3640     return Diag(Call->getLocEnd(),
3641                 diag::err_typecheck_call_too_few_args_at_least)
3642            << 0 /*function call*/ << 3 << Call->getNumArgs();
3643
3644   // Determine whether the current function is variadic or not.
3645   bool IsVariadic;
3646   if (BlockScopeInfo *CurBlock = getCurBlock())
3647     IsVariadic = CurBlock->TheDecl->isVariadic();
3648   else if (FunctionDecl *FD = getCurFunctionDecl())
3649     IsVariadic = FD->isVariadic();
3650   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3651     IsVariadic = MD->isVariadic();
3652   else
3653     llvm_unreachable("unexpected statement type");
3654
3655   if (!IsVariadic) {
3656     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3657     return true;
3658   }
3659
3660   // Type-check the first argument normally.
3661   if (checkBuiltinArgument(*this, Call, 0))
3662     return true;
3663
3664   const struct {
3665     unsigned ArgNo;
3666     QualType Type;
3667   } ArgumentTypes[] = {
3668     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3669     { 2, Context.getSizeType() },
3670   };
3671
3672   for (const auto &AT : ArgumentTypes) {
3673     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3674     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3675       continue;
3676     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3677       << Arg->getType() << AT.Type << 1 /* different class */
3678       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3679       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3680   }
3681
3682   return false;
3683 }
3684
3685 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3686 /// friends.  This is declared to take (...), so we have to check everything.
3687 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3688   if (TheCall->getNumArgs() < 2)
3689     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3690       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3691   if (TheCall->getNumArgs() > 2)
3692     return Diag(TheCall->getArg(2)->getLocStart(),
3693                 diag::err_typecheck_call_too_many_args)
3694       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3695       << SourceRange(TheCall->getArg(2)->getLocStart(),
3696                      (*(TheCall->arg_end()-1))->getLocEnd());
3697
3698   ExprResult OrigArg0 = TheCall->getArg(0);
3699   ExprResult OrigArg1 = TheCall->getArg(1);
3700
3701   // Do standard promotions between the two arguments, returning their common
3702   // type.
3703   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3704   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3705     return true;
3706
3707   // Make sure any conversions are pushed back into the call; this is
3708   // type safe since unordered compare builtins are declared as "_Bool
3709   // foo(...)".
3710   TheCall->setArg(0, OrigArg0.get());
3711   TheCall->setArg(1, OrigArg1.get());
3712
3713   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3714     return false;
3715
3716   // If the common type isn't a real floating type, then the arguments were
3717   // invalid for this operation.
3718   if (Res.isNull() || !Res->isRealFloatingType())
3719     return Diag(OrigArg0.get()->getLocStart(),
3720                 diag::err_typecheck_call_invalid_ordered_compare)
3721       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3722       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3723
3724   return false;
3725 }
3726
3727 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3728 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3729 /// to check everything. We expect the last argument to be a floating point
3730 /// value.
3731 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3732   if (TheCall->getNumArgs() < NumArgs)
3733     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3734       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3735   if (TheCall->getNumArgs() > NumArgs)
3736     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3737                 diag::err_typecheck_call_too_many_args)
3738       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3739       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3740                      (*(TheCall->arg_end()-1))->getLocEnd());
3741
3742   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3743
3744   if (OrigArg->isTypeDependent())
3745     return false;
3746
3747   // This operation requires a non-_Complex floating-point number.
3748   if (!OrigArg->getType()->isRealFloatingType())
3749     return Diag(OrigArg->getLocStart(),
3750                 diag::err_typecheck_call_invalid_unary_fp)
3751       << OrigArg->getType() << OrigArg->getSourceRange();
3752
3753   // If this is an implicit conversion from float -> float or double, remove it.
3754   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3755     // Only remove standard FloatCasts, leaving other casts inplace
3756     if (Cast->getCastKind() == CK_FloatingCast) {
3757       Expr *CastArg = Cast->getSubExpr();
3758       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3759           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3760                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3761                "promotion from float to either float or double is the only expected cast here");
3762         Cast->setSubExpr(nullptr);
3763         TheCall->setArg(NumArgs-1, CastArg);
3764       }
3765     }
3766   }
3767   
3768   return false;
3769 }
3770
3771 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3772 // This is declared to take (...), so we have to check everything.
3773 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3774   if (TheCall->getNumArgs() < 2)
3775     return ExprError(Diag(TheCall->getLocEnd(),
3776                           diag::err_typecheck_call_too_few_args_at_least)
3777                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3778                      << TheCall->getSourceRange());
3779
3780   // Determine which of the following types of shufflevector we're checking:
3781   // 1) unary, vector mask: (lhs, mask)
3782   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3783   QualType resType = TheCall->getArg(0)->getType();
3784   unsigned numElements = 0;
3785
3786   if (!TheCall->getArg(0)->isTypeDependent() &&
3787       !TheCall->getArg(1)->isTypeDependent()) {
3788     QualType LHSType = TheCall->getArg(0)->getType();
3789     QualType RHSType = TheCall->getArg(1)->getType();
3790
3791     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3792       return ExprError(Diag(TheCall->getLocStart(),
3793                             diag::err_shufflevector_non_vector)
3794                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3795                                       TheCall->getArg(1)->getLocEnd()));
3796
3797     numElements = LHSType->getAs<VectorType>()->getNumElements();
3798     unsigned numResElements = TheCall->getNumArgs() - 2;
3799
3800     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3801     // with mask.  If so, verify that RHS is an integer vector type with the
3802     // same number of elts as lhs.
3803     if (TheCall->getNumArgs() == 2) {
3804       if (!RHSType->hasIntegerRepresentation() ||
3805           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3806         return ExprError(Diag(TheCall->getLocStart(),
3807                               diag::err_shufflevector_incompatible_vector)
3808                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3809                                         TheCall->getArg(1)->getLocEnd()));
3810     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3811       return ExprError(Diag(TheCall->getLocStart(),
3812                             diag::err_shufflevector_incompatible_vector)
3813                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3814                                       TheCall->getArg(1)->getLocEnd()));
3815     } else if (numElements != numResElements) {
3816       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3817       resType = Context.getVectorType(eltType, numResElements,
3818                                       VectorType::GenericVector);
3819     }
3820   }
3821
3822   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3823     if (TheCall->getArg(i)->isTypeDependent() ||
3824         TheCall->getArg(i)->isValueDependent())
3825       continue;
3826
3827     llvm::APSInt Result(32);
3828     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3829       return ExprError(Diag(TheCall->getLocStart(),
3830                             diag::err_shufflevector_nonconstant_argument)
3831                        << TheCall->getArg(i)->getSourceRange());
3832
3833     // Allow -1 which will be translated to undef in the IR.
3834     if (Result.isSigned() && Result.isAllOnesValue())
3835       continue;
3836
3837     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3838       return ExprError(Diag(TheCall->getLocStart(),
3839                             diag::err_shufflevector_argument_too_large)
3840                        << TheCall->getArg(i)->getSourceRange());
3841   }
3842
3843   SmallVector<Expr*, 32> exprs;
3844
3845   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3846     exprs.push_back(TheCall->getArg(i));
3847     TheCall->setArg(i, nullptr);
3848   }
3849
3850   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3851                                          TheCall->getCallee()->getLocStart(),
3852                                          TheCall->getRParenLoc());
3853 }
3854
3855 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3856 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3857                                        SourceLocation BuiltinLoc,
3858                                        SourceLocation RParenLoc) {
3859   ExprValueKind VK = VK_RValue;
3860   ExprObjectKind OK = OK_Ordinary;
3861   QualType DstTy = TInfo->getType();
3862   QualType SrcTy = E->getType();
3863
3864   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3865     return ExprError(Diag(BuiltinLoc,
3866                           diag::err_convertvector_non_vector)
3867                      << E->getSourceRange());
3868   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3869     return ExprError(Diag(BuiltinLoc,
3870                           diag::err_convertvector_non_vector_type));
3871
3872   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3873     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3874     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3875     if (SrcElts != DstElts)
3876       return ExprError(Diag(BuiltinLoc,
3877                             diag::err_convertvector_incompatible_vector)
3878                        << E->getSourceRange());
3879   }
3880
3881   return new (Context)
3882       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3883 }
3884
3885 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3886 // This is declared to take (const void*, ...) and can take two
3887 // optional constant int args.
3888 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3889   unsigned NumArgs = TheCall->getNumArgs();
3890
3891   if (NumArgs > 3)
3892     return Diag(TheCall->getLocEnd(),
3893              diag::err_typecheck_call_too_many_args_at_most)
3894              << 0 /*function call*/ << 3 << NumArgs
3895              << TheCall->getSourceRange();
3896
3897   // Argument 0 is checked for us and the remaining arguments must be
3898   // constant integers.
3899   for (unsigned i = 1; i != NumArgs; ++i)
3900     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3901       return true;
3902
3903   return false;
3904 }
3905
3906 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3907 // __assume does not evaluate its arguments, and should warn if its argument
3908 // has side effects.
3909 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3910   Expr *Arg = TheCall->getArg(0);
3911   if (Arg->isInstantiationDependent()) return false;
3912
3913   if (Arg->HasSideEffects(Context))
3914     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3915       << Arg->getSourceRange()
3916       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3917
3918   return false;
3919 }
3920
3921 /// Handle __builtin_alloca_with_align. This is declared
3922 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3923 /// than 8.
3924 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3925   // The alignment must be a constant integer.
3926   Expr *Arg = TheCall->getArg(1);
3927
3928   // We can't check the value of a dependent argument.
3929   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3930     if (const auto *UE =
3931             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3932       if (UE->getKind() == UETT_AlignOf)
3933         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3934           << Arg->getSourceRange();
3935
3936     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3937
3938     if (!Result.isPowerOf2())
3939       return Diag(TheCall->getLocStart(),
3940                   diag::err_alignment_not_power_of_two)
3941            << Arg->getSourceRange();
3942
3943     if (Result < Context.getCharWidth())
3944       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3945            << (unsigned)Context.getCharWidth()
3946            << Arg->getSourceRange();
3947
3948     if (Result > INT32_MAX)
3949       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3950            << INT32_MAX
3951            << Arg->getSourceRange();
3952   }
3953
3954   return false;
3955 }
3956
3957 /// Handle __builtin_assume_aligned. This is declared
3958 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3959 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3960   unsigned NumArgs = TheCall->getNumArgs();
3961
3962   if (NumArgs > 3)
3963     return Diag(TheCall->getLocEnd(),
3964              diag::err_typecheck_call_too_many_args_at_most)
3965              << 0 /*function call*/ << 3 << NumArgs
3966              << TheCall->getSourceRange();
3967
3968   // The alignment must be a constant integer.
3969   Expr *Arg = TheCall->getArg(1);
3970
3971   // We can't check the value of a dependent argument.
3972   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3973     llvm::APSInt Result;
3974     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3975       return true;
3976
3977     if (!Result.isPowerOf2())
3978       return Diag(TheCall->getLocStart(),
3979                   diag::err_alignment_not_power_of_two)
3980            << Arg->getSourceRange();
3981   }
3982
3983   if (NumArgs > 2) {
3984     ExprResult Arg(TheCall->getArg(2));
3985     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3986       Context.getSizeType(), false);
3987     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3988     if (Arg.isInvalid()) return true;
3989     TheCall->setArg(2, Arg.get());
3990   }
3991
3992   return false;
3993 }
3994
3995 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3996   unsigned BuiltinID =
3997       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3998   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3999
4000   unsigned NumArgs = TheCall->getNumArgs();
4001   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4002   if (NumArgs < NumRequiredArgs) {
4003     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4004            << 0 /* function call */ << NumRequiredArgs << NumArgs
4005            << TheCall->getSourceRange();
4006   }
4007   if (NumArgs >= NumRequiredArgs + 0x100) {
4008     return Diag(TheCall->getLocEnd(),
4009                 diag::err_typecheck_call_too_many_args_at_most)
4010            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4011            << TheCall->getSourceRange();
4012   }
4013   unsigned i = 0;
4014
4015   // For formatting call, check buffer arg.
4016   if (!IsSizeCall) {
4017     ExprResult Arg(TheCall->getArg(i));
4018     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4019         Context, Context.VoidPtrTy, false);
4020     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4021     if (Arg.isInvalid())
4022       return true;
4023     TheCall->setArg(i, Arg.get());
4024     i++;
4025   }
4026
4027   // Check string literal arg.
4028   unsigned FormatIdx = i;
4029   {
4030     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4031     if (Arg.isInvalid())
4032       return true;
4033     TheCall->setArg(i, Arg.get());
4034     i++;
4035   }
4036
4037   // Make sure variadic args are scalar.
4038   unsigned FirstDataArg = i;
4039   while (i < NumArgs) {
4040     ExprResult Arg = DefaultVariadicArgumentPromotion(
4041         TheCall->getArg(i), VariadicFunction, nullptr);
4042     if (Arg.isInvalid())
4043       return true;
4044     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4045     if (ArgSize.getQuantity() >= 0x100) {
4046       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4047              << i << (int)ArgSize.getQuantity() << 0xff
4048              << TheCall->getSourceRange();
4049     }
4050     TheCall->setArg(i, Arg.get());
4051     i++;
4052   }
4053
4054   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4055   // call to avoid duplicate diagnostics.
4056   if (!IsSizeCall) {
4057     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4058     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4059     bool Success = CheckFormatArguments(
4060         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4061         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4062         CheckedVarArgs);
4063     if (!Success)
4064       return true;
4065   }
4066
4067   if (IsSizeCall) {
4068     TheCall->setType(Context.getSizeType());
4069   } else {
4070     TheCall->setType(Context.VoidPtrTy);
4071   }
4072   return false;
4073 }
4074
4075 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4076 /// TheCall is a constant expression.
4077 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4078                                   llvm::APSInt &Result) {
4079   Expr *Arg = TheCall->getArg(ArgNum);
4080   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4081   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4082   
4083   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4084   
4085   if (!Arg->isIntegerConstantExpr(Result, Context))
4086     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4087                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4088   
4089   return false;
4090 }
4091
4092 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4093 /// TheCall is a constant expression in the range [Low, High].
4094 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4095                                        int Low, int High) {
4096   llvm::APSInt Result;
4097
4098   // We can't check the value of a dependent argument.
4099   Expr *Arg = TheCall->getArg(ArgNum);
4100   if (Arg->isTypeDependent() || Arg->isValueDependent())
4101     return false;
4102
4103   // Check constant-ness first.
4104   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4105     return true;
4106
4107   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4108     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4109       << Low << High << Arg->getSourceRange();
4110
4111   return false;
4112 }
4113
4114 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4115 /// TheCall is a constant expression is a multiple of Num..
4116 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4117                                           unsigned Num) {
4118   llvm::APSInt Result;
4119
4120   // We can't check the value of a dependent argument.
4121   Expr *Arg = TheCall->getArg(ArgNum);
4122   if (Arg->isTypeDependent() || Arg->isValueDependent())
4123     return false;
4124
4125   // Check constant-ness first.
4126   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4127     return true;
4128
4129   if (Result.getSExtValue() % Num != 0)
4130     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4131       << Num << Arg->getSourceRange();
4132
4133   return false;
4134 }
4135
4136 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4137 /// TheCall is an ARM/AArch64 special register string literal.
4138 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4139                                     int ArgNum, unsigned ExpectedFieldNum,
4140                                     bool AllowName) {
4141   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4142                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4143                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4144                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4145                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4146                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4147   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4148                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4149                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4150                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4151                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4152                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4153   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4154
4155   // We can't check the value of a dependent argument.
4156   Expr *Arg = TheCall->getArg(ArgNum);
4157   if (Arg->isTypeDependent() || Arg->isValueDependent())
4158     return false;
4159
4160   // Check if the argument is a string literal.
4161   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4162     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4163            << Arg->getSourceRange();
4164
4165   // Check the type of special register given.
4166   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4167   SmallVector<StringRef, 6> Fields;
4168   Reg.split(Fields, ":");
4169
4170   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4171     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4172            << Arg->getSourceRange();
4173
4174   // If the string is the name of a register then we cannot check that it is
4175   // valid here but if the string is of one the forms described in ACLE then we
4176   // can check that the supplied fields are integers and within the valid
4177   // ranges.
4178   if (Fields.size() > 1) {
4179     bool FiveFields = Fields.size() == 5;
4180
4181     bool ValidString = true;
4182     if (IsARMBuiltin) {
4183       ValidString &= Fields[0].startswith_lower("cp") ||
4184                      Fields[0].startswith_lower("p");
4185       if (ValidString)
4186         Fields[0] =
4187           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4188
4189       ValidString &= Fields[2].startswith_lower("c");
4190       if (ValidString)
4191         Fields[2] = Fields[2].drop_front(1);
4192
4193       if (FiveFields) {
4194         ValidString &= Fields[3].startswith_lower("c");
4195         if (ValidString)
4196           Fields[3] = Fields[3].drop_front(1);
4197       }
4198     }
4199
4200     SmallVector<int, 5> Ranges;
4201     if (FiveFields)
4202       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4203     else
4204       Ranges.append({15, 7, 15});
4205
4206     for (unsigned i=0; i<Fields.size(); ++i) {
4207       int IntField;
4208       ValidString &= !Fields[i].getAsInteger(10, IntField);
4209       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4210     }
4211
4212     if (!ValidString)
4213       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4214              << Arg->getSourceRange();
4215
4216   } else if (IsAArch64Builtin && Fields.size() == 1) {
4217     // If the register name is one of those that appear in the condition below
4218     // and the special register builtin being used is one of the write builtins,
4219     // then we require that the argument provided for writing to the register
4220     // is an integer constant expression. This is because it will be lowered to
4221     // an MSR (immediate) instruction, so we need to know the immediate at
4222     // compile time.
4223     if (TheCall->getNumArgs() != 2)
4224       return false;
4225
4226     std::string RegLower = Reg.lower();
4227     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4228         RegLower != "pan" && RegLower != "uao")
4229       return false;
4230
4231     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4232   }
4233
4234   return false;
4235 }
4236
4237 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4238 /// This checks that the target supports __builtin_longjmp and
4239 /// that val is a constant 1.
4240 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4241   if (!Context.getTargetInfo().hasSjLjLowering())
4242     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4243              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4244
4245   Expr *Arg = TheCall->getArg(1);
4246   llvm::APSInt Result;
4247
4248   // TODO: This is less than ideal. Overload this to take a value.
4249   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4250     return true;
4251   
4252   if (Result != 1)
4253     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4254              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4255
4256   return false;
4257 }
4258
4259 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4260 /// This checks that the target supports __builtin_setjmp.
4261 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4262   if (!Context.getTargetInfo().hasSjLjLowering())
4263     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4264              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4265   return false;
4266 }
4267
4268 namespace {
4269 class UncoveredArgHandler {
4270   enum { Unknown = -1, AllCovered = -2 };
4271   signed FirstUncoveredArg;
4272   SmallVector<const Expr *, 4> DiagnosticExprs;
4273
4274 public:
4275   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4276
4277   bool hasUncoveredArg() const {
4278     return (FirstUncoveredArg >= 0);
4279   }
4280
4281   unsigned getUncoveredArg() const {
4282     assert(hasUncoveredArg() && "no uncovered argument");
4283     return FirstUncoveredArg;
4284   }
4285
4286   void setAllCovered() {
4287     // A string has been found with all arguments covered, so clear out
4288     // the diagnostics.
4289     DiagnosticExprs.clear();
4290     FirstUncoveredArg = AllCovered;
4291   }
4292
4293   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4294     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4295
4296     // Don't update if a previous string covers all arguments.
4297     if (FirstUncoveredArg == AllCovered)
4298       return;
4299
4300     // UncoveredArgHandler tracks the highest uncovered argument index
4301     // and with it all the strings that match this index.
4302     if (NewFirstUncoveredArg == FirstUncoveredArg)
4303       DiagnosticExprs.push_back(StrExpr);
4304     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4305       DiagnosticExprs.clear();
4306       DiagnosticExprs.push_back(StrExpr);
4307       FirstUncoveredArg = NewFirstUncoveredArg;
4308     }
4309   }
4310
4311   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4312 };
4313
4314 enum StringLiteralCheckType {
4315   SLCT_NotALiteral,
4316   SLCT_UncheckedLiteral,
4317   SLCT_CheckedLiteral
4318 };
4319 } // end anonymous namespace
4320
4321 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4322                                      BinaryOperatorKind BinOpKind,
4323                                      bool AddendIsRight) {
4324   unsigned BitWidth = Offset.getBitWidth();
4325   unsigned AddendBitWidth = Addend.getBitWidth();
4326   // There might be negative interim results.
4327   if (Addend.isUnsigned()) {
4328     Addend = Addend.zext(++AddendBitWidth);
4329     Addend.setIsSigned(true);
4330   }
4331   // Adjust the bit width of the APSInts.
4332   if (AddendBitWidth > BitWidth) {
4333     Offset = Offset.sext(AddendBitWidth);
4334     BitWidth = AddendBitWidth;
4335   } else if (BitWidth > AddendBitWidth) {
4336     Addend = Addend.sext(BitWidth);
4337   }
4338
4339   bool Ov = false;
4340   llvm::APSInt ResOffset = Offset;
4341   if (BinOpKind == BO_Add)
4342     ResOffset = Offset.sadd_ov(Addend, Ov);
4343   else {
4344     assert(AddendIsRight && BinOpKind == BO_Sub &&
4345            "operator must be add or sub with addend on the right");
4346     ResOffset = Offset.ssub_ov(Addend, Ov);
4347   }
4348
4349   // We add an offset to a pointer here so we should support an offset as big as
4350   // possible.
4351   if (Ov) {
4352     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4353     Offset = Offset.sext(2 * BitWidth);
4354     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4355     return;
4356   }
4357
4358   Offset = ResOffset;
4359 }
4360
4361 namespace {
4362 // This is a wrapper class around StringLiteral to support offsetted string
4363 // literals as format strings. It takes the offset into account when returning
4364 // the string and its length or the source locations to display notes correctly.
4365 class FormatStringLiteral {
4366   const StringLiteral *FExpr;
4367   int64_t Offset;
4368
4369  public:
4370   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4371       : FExpr(fexpr), Offset(Offset) {}
4372
4373   StringRef getString() const {
4374     return FExpr->getString().drop_front(Offset);
4375   }
4376
4377   unsigned getByteLength() const {
4378     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4379   }
4380   unsigned getLength() const { return FExpr->getLength() - Offset; }
4381   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4382
4383   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4384
4385   QualType getType() const { return FExpr->getType(); }
4386
4387   bool isAscii() const { return FExpr->isAscii(); }
4388   bool isWide() const { return FExpr->isWide(); }
4389   bool isUTF8() const { return FExpr->isUTF8(); }
4390   bool isUTF16() const { return FExpr->isUTF16(); }
4391   bool isUTF32() const { return FExpr->isUTF32(); }
4392   bool isPascal() const { return FExpr->isPascal(); }
4393
4394   SourceLocation getLocationOfByte(
4395       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4396       const TargetInfo &Target, unsigned *StartToken = nullptr,
4397       unsigned *StartTokenByteOffset = nullptr) const {
4398     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4399                                     StartToken, StartTokenByteOffset);
4400   }
4401
4402   SourceLocation getLocStart() const LLVM_READONLY {
4403     return FExpr->getLocStart().getLocWithOffset(Offset);
4404   }
4405   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4406 };
4407 }  // end anonymous namespace
4408
4409 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4410                               const Expr *OrigFormatExpr,
4411                               ArrayRef<const Expr *> Args,
4412                               bool HasVAListArg, unsigned format_idx,
4413                               unsigned firstDataArg,
4414                               Sema::FormatStringType Type,
4415                               bool inFunctionCall,
4416                               Sema::VariadicCallType CallType,
4417                               llvm::SmallBitVector &CheckedVarArgs,
4418                               UncoveredArgHandler &UncoveredArg);
4419
4420 // Determine if an expression is a string literal or constant string.
4421 // If this function returns false on the arguments to a function expecting a
4422 // format string, we will usually need to emit a warning.
4423 // True string literals are then checked by CheckFormatString.
4424 static StringLiteralCheckType
4425 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4426                       bool HasVAListArg, unsigned format_idx,
4427                       unsigned firstDataArg, Sema::FormatStringType Type,
4428                       Sema::VariadicCallType CallType, bool InFunctionCall,
4429                       llvm::SmallBitVector &CheckedVarArgs,
4430                       UncoveredArgHandler &UncoveredArg,
4431                       llvm::APSInt Offset) {
4432  tryAgain:
4433   assert(Offset.isSigned() && "invalid offset");
4434
4435   if (E->isTypeDependent() || E->isValueDependent())
4436     return SLCT_NotALiteral;
4437
4438   E = E->IgnoreParenCasts();
4439
4440   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4441     // Technically -Wformat-nonliteral does not warn about this case.
4442     // The behavior of printf and friends in this case is implementation
4443     // dependent.  Ideally if the format string cannot be null then
4444     // it should have a 'nonnull' attribute in the function prototype.
4445     return SLCT_UncheckedLiteral;
4446
4447   switch (E->getStmtClass()) {
4448   case Stmt::BinaryConditionalOperatorClass:
4449   case Stmt::ConditionalOperatorClass: {
4450     // The expression is a literal if both sub-expressions were, and it was
4451     // completely checked only if both sub-expressions were checked.
4452     const AbstractConditionalOperator *C =
4453         cast<AbstractConditionalOperator>(E);
4454
4455     // Determine whether it is necessary to check both sub-expressions, for
4456     // example, because the condition expression is a constant that can be
4457     // evaluated at compile time.
4458     bool CheckLeft = true, CheckRight = true;
4459
4460     bool Cond;
4461     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4462       if (Cond)
4463         CheckRight = false;
4464       else
4465         CheckLeft = false;
4466     }
4467
4468     // We need to maintain the offsets for the right and the left hand side
4469     // separately to check if every possible indexed expression is a valid
4470     // string literal. They might have different offsets for different string
4471     // literals in the end.
4472     StringLiteralCheckType Left;
4473     if (!CheckLeft)
4474       Left = SLCT_UncheckedLiteral;
4475     else {
4476       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4477                                    HasVAListArg, format_idx, firstDataArg,
4478                                    Type, CallType, InFunctionCall,
4479                                    CheckedVarArgs, UncoveredArg, Offset);
4480       if (Left == SLCT_NotALiteral || !CheckRight) {
4481         return Left;
4482       }
4483     }
4484
4485     StringLiteralCheckType Right =
4486         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4487                               HasVAListArg, format_idx, firstDataArg,
4488                               Type, CallType, InFunctionCall, CheckedVarArgs,
4489                               UncoveredArg, Offset);
4490
4491     return (CheckLeft && Left < Right) ? Left : Right;
4492   }
4493
4494   case Stmt::ImplicitCastExprClass: {
4495     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4496     goto tryAgain;
4497   }
4498
4499   case Stmt::OpaqueValueExprClass:
4500     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4501       E = src;
4502       goto tryAgain;
4503     }
4504     return SLCT_NotALiteral;
4505
4506   case Stmt::PredefinedExprClass:
4507     // While __func__, etc., are technically not string literals, they
4508     // cannot contain format specifiers and thus are not a security
4509     // liability.
4510     return SLCT_UncheckedLiteral;
4511       
4512   case Stmt::DeclRefExprClass: {
4513     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4514
4515     // As an exception, do not flag errors for variables binding to
4516     // const string literals.
4517     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4518       bool isConstant = false;
4519       QualType T = DR->getType();
4520
4521       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4522         isConstant = AT->getElementType().isConstant(S.Context);
4523       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4524         isConstant = T.isConstant(S.Context) &&
4525                      PT->getPointeeType().isConstant(S.Context);
4526       } else if (T->isObjCObjectPointerType()) {
4527         // In ObjC, there is usually no "const ObjectPointer" type,
4528         // so don't check if the pointee type is constant.
4529         isConstant = T.isConstant(S.Context);
4530       }
4531
4532       if (isConstant) {
4533         if (const Expr *Init = VD->getAnyInitializer()) {
4534           // Look through initializers like const char c[] = { "foo" }
4535           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4536             if (InitList->isStringLiteralInit())
4537               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4538           }
4539           return checkFormatStringExpr(S, Init, Args,
4540                                        HasVAListArg, format_idx,
4541                                        firstDataArg, Type, CallType,
4542                                        /*InFunctionCall*/ false, CheckedVarArgs,
4543                                        UncoveredArg, Offset);
4544         }
4545       }
4546
4547       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4548       // special check to see if the format string is a function parameter
4549       // of the function calling the printf function.  If the function
4550       // has an attribute indicating it is a printf-like function, then we
4551       // should suppress warnings concerning non-literals being used in a call
4552       // to a vprintf function.  For example:
4553       //
4554       // void
4555       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4556       //      va_list ap;
4557       //      va_start(ap, fmt);
4558       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4559       //      ...
4560       // }
4561       if (HasVAListArg) {
4562         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4563           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4564             int PVIndex = PV->getFunctionScopeIndex() + 1;
4565             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4566               // adjust for implicit parameter
4567               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4568                 if (MD->isInstance())
4569                   ++PVIndex;
4570               // We also check if the formats are compatible.
4571               // We can't pass a 'scanf' string to a 'printf' function.
4572               if (PVIndex == PVFormat->getFormatIdx() &&
4573                   Type == S.GetFormatStringType(PVFormat))
4574                 return SLCT_UncheckedLiteral;
4575             }
4576           }
4577         }
4578       }
4579     }
4580
4581     return SLCT_NotALiteral;
4582   }
4583
4584   case Stmt::CallExprClass:
4585   case Stmt::CXXMemberCallExprClass: {
4586     const CallExpr *CE = cast<CallExpr>(E);
4587     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4588       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4589         unsigned ArgIndex = FA->getFormatIdx();
4590         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4591           if (MD->isInstance())
4592             --ArgIndex;
4593         const Expr *Arg = CE->getArg(ArgIndex - 1);
4594
4595         return checkFormatStringExpr(S, Arg, Args,
4596                                      HasVAListArg, format_idx, firstDataArg,
4597                                      Type, CallType, InFunctionCall,
4598                                      CheckedVarArgs, UncoveredArg, Offset);
4599       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4600         unsigned BuiltinID = FD->getBuiltinID();
4601         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4602             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4603           const Expr *Arg = CE->getArg(0);
4604           return checkFormatStringExpr(S, Arg, Args,
4605                                        HasVAListArg, format_idx,
4606                                        firstDataArg, Type, CallType,
4607                                        InFunctionCall, CheckedVarArgs,
4608                                        UncoveredArg, Offset);
4609         }
4610       }
4611     }
4612
4613     return SLCT_NotALiteral;
4614   }
4615   case Stmt::ObjCMessageExprClass: {
4616     const auto *ME = cast<ObjCMessageExpr>(E);
4617     if (const auto *ND = ME->getMethodDecl()) {
4618       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4619         unsigned ArgIndex = FA->getFormatIdx();
4620         const Expr *Arg = ME->getArg(ArgIndex - 1);
4621         return checkFormatStringExpr(
4622             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4623             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4624       }
4625     }
4626
4627     return SLCT_NotALiteral;
4628   }
4629   case Stmt::ObjCStringLiteralClass:
4630   case Stmt::StringLiteralClass: {
4631     const StringLiteral *StrE = nullptr;
4632
4633     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4634       StrE = ObjCFExpr->getString();
4635     else
4636       StrE = cast<StringLiteral>(E);
4637
4638     if (StrE) {
4639       if (Offset.isNegative() || Offset > StrE->getLength()) {
4640         // TODO: It would be better to have an explicit warning for out of
4641         // bounds literals.
4642         return SLCT_NotALiteral;
4643       }
4644       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4645       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4646                         firstDataArg, Type, InFunctionCall, CallType,
4647                         CheckedVarArgs, UncoveredArg);
4648       return SLCT_CheckedLiteral;
4649     }
4650
4651     return SLCT_NotALiteral;
4652   }
4653   case Stmt::BinaryOperatorClass: {
4654     llvm::APSInt LResult;
4655     llvm::APSInt RResult;
4656
4657     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4658
4659     // A string literal + an int offset is still a string literal.
4660     if (BinOp->isAdditiveOp()) {
4661       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4662       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4663
4664       if (LIsInt != RIsInt) {
4665         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4666
4667         if (LIsInt) {
4668           if (BinOpKind == BO_Add) {
4669             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4670             E = BinOp->getRHS();
4671             goto tryAgain;
4672           }
4673         } else {
4674           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4675           E = BinOp->getLHS();
4676           goto tryAgain;
4677         }
4678       }
4679     }
4680
4681     return SLCT_NotALiteral;
4682   }
4683   case Stmt::UnaryOperatorClass: {
4684     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4685     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4686     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4687       llvm::APSInt IndexResult;
4688       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4689         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4690         E = ASE->getBase();
4691         goto tryAgain;
4692       }
4693     }
4694
4695     return SLCT_NotALiteral;
4696   }
4697
4698   default:
4699     return SLCT_NotALiteral;
4700   }
4701 }
4702
4703 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4704   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4705       .Case("scanf", FST_Scanf)
4706       .Cases("printf", "printf0", FST_Printf)
4707       .Cases("NSString", "CFString", FST_NSString)
4708       .Case("strftime", FST_Strftime)
4709       .Case("strfmon", FST_Strfmon)
4710       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4711       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4712       .Case("os_trace", FST_OSLog)
4713       .Case("os_log", FST_OSLog)
4714       .Default(FST_Unknown);
4715 }
4716
4717 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4718 /// functions) for correct use of format strings.
4719 /// Returns true if a format string has been fully checked.
4720 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4721                                 ArrayRef<const Expr *> Args,
4722                                 bool IsCXXMember,
4723                                 VariadicCallType CallType,
4724                                 SourceLocation Loc, SourceRange Range,
4725                                 llvm::SmallBitVector &CheckedVarArgs) {
4726   FormatStringInfo FSI;
4727   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4728     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4729                                 FSI.FirstDataArg, GetFormatStringType(Format),
4730                                 CallType, Loc, Range, CheckedVarArgs);
4731   return false;
4732 }
4733
4734 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4735                                 bool HasVAListArg, unsigned format_idx,
4736                                 unsigned firstDataArg, FormatStringType Type,
4737                                 VariadicCallType CallType,
4738                                 SourceLocation Loc, SourceRange Range,
4739                                 llvm::SmallBitVector &CheckedVarArgs) {
4740   // CHECK: printf/scanf-like function is called with no format string.
4741   if (format_idx >= Args.size()) {
4742     Diag(Loc, diag::warn_missing_format_string) << Range;
4743     return false;
4744   }
4745
4746   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4747
4748   // CHECK: format string is not a string literal.
4749   //
4750   // Dynamically generated format strings are difficult to
4751   // automatically vet at compile time.  Requiring that format strings
4752   // are string literals: (1) permits the checking of format strings by
4753   // the compiler and thereby (2) can practically remove the source of
4754   // many format string exploits.
4755
4756   // Format string can be either ObjC string (e.g. @"%d") or
4757   // C string (e.g. "%d")
4758   // ObjC string uses the same format specifiers as C string, so we can use
4759   // the same format string checking logic for both ObjC and C strings.
4760   UncoveredArgHandler UncoveredArg;
4761   StringLiteralCheckType CT =
4762       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4763                             format_idx, firstDataArg, Type, CallType,
4764                             /*IsFunctionCall*/ true, CheckedVarArgs,
4765                             UncoveredArg,
4766                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4767
4768   // Generate a diagnostic where an uncovered argument is detected.
4769   if (UncoveredArg.hasUncoveredArg()) {
4770     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4771     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4772     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4773   }
4774
4775   if (CT != SLCT_NotALiteral)
4776     // Literal format string found, check done!
4777     return CT == SLCT_CheckedLiteral;
4778
4779   // Strftime is particular as it always uses a single 'time' argument,
4780   // so it is safe to pass a non-literal string.
4781   if (Type == FST_Strftime)
4782     return false;
4783
4784   // Do not emit diag when the string param is a macro expansion and the
4785   // format is either NSString or CFString. This is a hack to prevent
4786   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4787   // which are usually used in place of NS and CF string literals.
4788   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4789   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4790     return false;
4791
4792   // If there are no arguments specified, warn with -Wformat-security, otherwise
4793   // warn only with -Wformat-nonliteral.
4794   if (Args.size() == firstDataArg) {
4795     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4796       << OrigFormatExpr->getSourceRange();
4797     switch (Type) {
4798     default:
4799       break;
4800     case FST_Kprintf:
4801     case FST_FreeBSDKPrintf:
4802     case FST_Printf:
4803       Diag(FormatLoc, diag::note_format_security_fixit)
4804         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4805       break;
4806     case FST_NSString:
4807       Diag(FormatLoc, diag::note_format_security_fixit)
4808         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4809       break;
4810     }
4811   } else {
4812     Diag(FormatLoc, diag::warn_format_nonliteral)
4813       << OrigFormatExpr->getSourceRange();
4814   }
4815   return false;
4816 }
4817
4818 namespace {
4819 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4820 protected:
4821   Sema &S;
4822   const FormatStringLiteral *FExpr;
4823   const Expr *OrigFormatExpr;
4824   const Sema::FormatStringType FSType;
4825   const unsigned FirstDataArg;
4826   const unsigned NumDataArgs;
4827   const char *Beg; // Start of format string.
4828   const bool HasVAListArg;
4829   ArrayRef<const Expr *> Args;
4830   unsigned FormatIdx;
4831   llvm::SmallBitVector CoveredArgs;
4832   bool usesPositionalArgs;
4833   bool atFirstArg;
4834   bool inFunctionCall;
4835   Sema::VariadicCallType CallType;
4836   llvm::SmallBitVector &CheckedVarArgs;
4837   UncoveredArgHandler &UncoveredArg;
4838
4839 public:
4840   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4841                      const Expr *origFormatExpr,
4842                      const Sema::FormatStringType type, unsigned firstDataArg,
4843                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4844                      ArrayRef<const Expr *> Args, unsigned formatIdx,
4845                      bool inFunctionCall, Sema::VariadicCallType callType,
4846                      llvm::SmallBitVector &CheckedVarArgs,
4847                      UncoveredArgHandler &UncoveredArg)
4848       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4849         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4850         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4851         usesPositionalArgs(false), atFirstArg(true),
4852         inFunctionCall(inFunctionCall), CallType(callType),
4853         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4854     CoveredArgs.resize(numDataArgs);
4855     CoveredArgs.reset();
4856   }
4857
4858   void DoneProcessing();
4859
4860   void HandleIncompleteSpecifier(const char *startSpecifier,
4861                                  unsigned specifierLen) override;
4862
4863   void HandleInvalidLengthModifier(
4864                            const analyze_format_string::FormatSpecifier &FS,
4865                            const analyze_format_string::ConversionSpecifier &CS,
4866                            const char *startSpecifier, unsigned specifierLen,
4867                            unsigned DiagID);
4868
4869   void HandleNonStandardLengthModifier(
4870                     const analyze_format_string::FormatSpecifier &FS,
4871                     const char *startSpecifier, unsigned specifierLen);
4872
4873   void HandleNonStandardConversionSpecifier(
4874                     const analyze_format_string::ConversionSpecifier &CS,
4875                     const char *startSpecifier, unsigned specifierLen);
4876
4877   void HandlePosition(const char *startPos, unsigned posLen) override;
4878
4879   void HandleInvalidPosition(const char *startSpecifier,
4880                              unsigned specifierLen,
4881                              analyze_format_string::PositionContext p) override;
4882
4883   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4884
4885   void HandleNullChar(const char *nullCharacter) override;
4886
4887   template <typename Range>
4888   static void
4889   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4890                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4891                        bool IsStringLocation, Range StringRange,
4892                        ArrayRef<FixItHint> Fixit = None);
4893
4894 protected:
4895   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4896                                         const char *startSpec,
4897                                         unsigned specifierLen,
4898                                         const char *csStart, unsigned csLen);
4899
4900   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4901                                          const char *startSpec,
4902                                          unsigned specifierLen);
4903   
4904   SourceRange getFormatStringRange();
4905   CharSourceRange getSpecifierRange(const char *startSpecifier,
4906                                     unsigned specifierLen);
4907   SourceLocation getLocationOfByte(const char *x);
4908
4909   const Expr *getDataArg(unsigned i) const;
4910   
4911   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4912                     const analyze_format_string::ConversionSpecifier &CS,
4913                     const char *startSpecifier, unsigned specifierLen,
4914                     unsigned argIndex);
4915
4916   template <typename Range>
4917   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4918                             bool IsStringLocation, Range StringRange,
4919                             ArrayRef<FixItHint> Fixit = None);
4920 };
4921 } // end anonymous namespace
4922
4923 SourceRange CheckFormatHandler::getFormatStringRange() {
4924   return OrigFormatExpr->getSourceRange();
4925 }
4926
4927 CharSourceRange CheckFormatHandler::
4928 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4929   SourceLocation Start = getLocationOfByte(startSpecifier);
4930   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4931
4932   // Advance the end SourceLocation by one due to half-open ranges.
4933   End = End.getLocWithOffset(1);
4934
4935   return CharSourceRange::getCharRange(Start, End);
4936 }
4937
4938 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4939   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4940                                   S.getLangOpts(), S.Context.getTargetInfo());
4941 }
4942
4943 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4944                                                    unsigned specifierLen){
4945   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4946                        getLocationOfByte(startSpecifier),
4947                        /*IsStringLocation*/true,
4948                        getSpecifierRange(startSpecifier, specifierLen));
4949 }
4950
4951 void CheckFormatHandler::HandleInvalidLengthModifier(
4952     const analyze_format_string::FormatSpecifier &FS,
4953     const analyze_format_string::ConversionSpecifier &CS,
4954     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4955   using namespace analyze_format_string;
4956
4957   const LengthModifier &LM = FS.getLengthModifier();
4958   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4959
4960   // See if we know how to fix this length modifier.
4961   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4962   if (FixedLM) {
4963     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4964                          getLocationOfByte(LM.getStart()),
4965                          /*IsStringLocation*/true,
4966                          getSpecifierRange(startSpecifier, specifierLen));
4967
4968     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4969       << FixedLM->toString()
4970       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4971
4972   } else {
4973     FixItHint Hint;
4974     if (DiagID == diag::warn_format_nonsensical_length)
4975       Hint = FixItHint::CreateRemoval(LMRange);
4976
4977     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4978                          getLocationOfByte(LM.getStart()),
4979                          /*IsStringLocation*/true,
4980                          getSpecifierRange(startSpecifier, specifierLen),
4981                          Hint);
4982   }
4983 }
4984
4985 void CheckFormatHandler::HandleNonStandardLengthModifier(
4986     const analyze_format_string::FormatSpecifier &FS,
4987     const char *startSpecifier, unsigned specifierLen) {
4988   using namespace analyze_format_string;
4989
4990   const LengthModifier &LM = FS.getLengthModifier();
4991   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4992
4993   // See if we know how to fix this length modifier.
4994   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4995   if (FixedLM) {
4996     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4997                            << LM.toString() << 0,
4998                          getLocationOfByte(LM.getStart()),
4999                          /*IsStringLocation*/true,
5000                          getSpecifierRange(startSpecifier, specifierLen));
5001
5002     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5003       << FixedLM->toString()
5004       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5005
5006   } else {
5007     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5008                            << LM.toString() << 0,
5009                          getLocationOfByte(LM.getStart()),
5010                          /*IsStringLocation*/true,
5011                          getSpecifierRange(startSpecifier, specifierLen));
5012   }
5013 }
5014
5015 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5016     const analyze_format_string::ConversionSpecifier &CS,
5017     const char *startSpecifier, unsigned specifierLen) {
5018   using namespace analyze_format_string;
5019
5020   // See if we know how to fix this conversion specifier.
5021   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5022   if (FixedCS) {
5023     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5024                           << CS.toString() << /*conversion specifier*/1,
5025                          getLocationOfByte(CS.getStart()),
5026                          /*IsStringLocation*/true,
5027                          getSpecifierRange(startSpecifier, specifierLen));
5028
5029     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5030     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5031       << FixedCS->toString()
5032       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5033   } else {
5034     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5035                           << CS.toString() << /*conversion specifier*/1,
5036                          getLocationOfByte(CS.getStart()),
5037                          /*IsStringLocation*/true,
5038                          getSpecifierRange(startSpecifier, specifierLen));
5039   }
5040 }
5041
5042 void CheckFormatHandler::HandlePosition(const char *startPos,
5043                                         unsigned posLen) {
5044   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5045                                getLocationOfByte(startPos),
5046                                /*IsStringLocation*/true,
5047                                getSpecifierRange(startPos, posLen));
5048 }
5049
5050 void
5051 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5052                                      analyze_format_string::PositionContext p) {
5053   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5054                          << (unsigned) p,
5055                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5056                        getSpecifierRange(startPos, posLen));
5057 }
5058
5059 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5060                                             unsigned posLen) {
5061   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5062                                getLocationOfByte(startPos),
5063                                /*IsStringLocation*/true,
5064                                getSpecifierRange(startPos, posLen));
5065 }
5066
5067 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5068   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5069     // The presence of a null character is likely an error.
5070     EmitFormatDiagnostic(
5071       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5072       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5073       getFormatStringRange());
5074   }
5075 }
5076
5077 // Note that this may return NULL if there was an error parsing or building
5078 // one of the argument expressions.
5079 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5080   return Args[FirstDataArg + i];
5081 }
5082
5083 void CheckFormatHandler::DoneProcessing() {
5084   // Does the number of data arguments exceed the number of
5085   // format conversions in the format string?
5086   if (!HasVAListArg) {
5087       // Find any arguments that weren't covered.
5088     CoveredArgs.flip();
5089     signed notCoveredArg = CoveredArgs.find_first();
5090     if (notCoveredArg >= 0) {
5091       assert((unsigned)notCoveredArg < NumDataArgs);
5092       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5093     } else {
5094       UncoveredArg.setAllCovered();
5095     }
5096   }
5097 }
5098
5099 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5100                                    const Expr *ArgExpr) {
5101   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5102          "Invalid state");
5103
5104   if (!ArgExpr)
5105     return;
5106
5107   SourceLocation Loc = ArgExpr->getLocStart();
5108
5109   if (S.getSourceManager().isInSystemMacro(Loc))
5110     return;
5111
5112   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5113   for (auto E : DiagnosticExprs)
5114     PDiag << E->getSourceRange();
5115
5116   CheckFormatHandler::EmitFormatDiagnostic(
5117                                   S, IsFunctionCall, DiagnosticExprs[0],
5118                                   PDiag, Loc, /*IsStringLocation*/false,
5119                                   DiagnosticExprs[0]->getSourceRange());
5120 }
5121
5122 bool
5123 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5124                                                      SourceLocation Loc,
5125                                                      const char *startSpec,
5126                                                      unsigned specifierLen,
5127                                                      const char *csStart,
5128                                                      unsigned csLen) {
5129   bool keepGoing = true;
5130   if (argIndex < NumDataArgs) {
5131     // Consider the argument coverered, even though the specifier doesn't
5132     // make sense.
5133     CoveredArgs.set(argIndex);
5134   }
5135   else {
5136     // If argIndex exceeds the number of data arguments we
5137     // don't issue a warning because that is just a cascade of warnings (and
5138     // they may have intended '%%' anyway). We don't want to continue processing
5139     // the format string after this point, however, as we will like just get
5140     // gibberish when trying to match arguments.
5141     keepGoing = false;
5142   }
5143
5144   StringRef Specifier(csStart, csLen);
5145
5146   // If the specifier in non-printable, it could be the first byte of a UTF-8
5147   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5148   // hex value.
5149   std::string CodePointStr;
5150   if (!llvm::sys::locale::isPrint(*csStart)) {
5151     llvm::UTF32 CodePoint;
5152     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5153     const llvm::UTF8 *E =
5154         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5155     llvm::ConversionResult Result =
5156         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5157
5158     if (Result != llvm::conversionOK) {
5159       unsigned char FirstChar = *csStart;
5160       CodePoint = (llvm::UTF32)FirstChar;
5161     }
5162
5163     llvm::raw_string_ostream OS(CodePointStr);
5164     if (CodePoint < 256)
5165       OS << "\\x" << llvm::format("%02x", CodePoint);
5166     else if (CodePoint <= 0xFFFF)
5167       OS << "\\u" << llvm::format("%04x", CodePoint);
5168     else
5169       OS << "\\U" << llvm::format("%08x", CodePoint);
5170     OS.flush();
5171     Specifier = CodePointStr;
5172   }
5173
5174   EmitFormatDiagnostic(
5175       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5176       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5177
5178   return keepGoing;
5179 }
5180
5181 void
5182 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5183                                                       const char *startSpec,
5184                                                       unsigned specifierLen) {
5185   EmitFormatDiagnostic(
5186     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5187     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5188 }
5189
5190 bool
5191 CheckFormatHandler::CheckNumArgs(
5192   const analyze_format_string::FormatSpecifier &FS,
5193   const analyze_format_string::ConversionSpecifier &CS,
5194   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5195
5196   if (argIndex >= NumDataArgs) {
5197     PartialDiagnostic PDiag = FS.usesPositionalArg()
5198       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5199            << (argIndex+1) << NumDataArgs)
5200       : S.PDiag(diag::warn_printf_insufficient_data_args);
5201     EmitFormatDiagnostic(
5202       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5203       getSpecifierRange(startSpecifier, specifierLen));
5204
5205     // Since more arguments than conversion tokens are given, by extension
5206     // all arguments are covered, so mark this as so.
5207     UncoveredArg.setAllCovered();
5208     return false;
5209   }
5210   return true;
5211 }
5212
5213 template<typename Range>
5214 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5215                                               SourceLocation Loc,
5216                                               bool IsStringLocation,
5217                                               Range StringRange,
5218                                               ArrayRef<FixItHint> FixIt) {
5219   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5220                        Loc, IsStringLocation, StringRange, FixIt);
5221 }
5222
5223 /// \brief If the format string is not within the funcion call, emit a note
5224 /// so that the function call and string are in diagnostic messages.
5225 ///
5226 /// \param InFunctionCall if true, the format string is within the function
5227 /// call and only one diagnostic message will be produced.  Otherwise, an
5228 /// extra note will be emitted pointing to location of the format string.
5229 ///
5230 /// \param ArgumentExpr the expression that is passed as the format string
5231 /// argument in the function call.  Used for getting locations when two
5232 /// diagnostics are emitted.
5233 ///
5234 /// \param PDiag the callee should already have provided any strings for the
5235 /// diagnostic message.  This function only adds locations and fixits
5236 /// to diagnostics.
5237 ///
5238 /// \param Loc primary location for diagnostic.  If two diagnostics are
5239 /// required, one will be at Loc and a new SourceLocation will be created for
5240 /// the other one.
5241 ///
5242 /// \param IsStringLocation if true, Loc points to the format string should be
5243 /// used for the note.  Otherwise, Loc points to the argument list and will
5244 /// be used with PDiag.
5245 ///
5246 /// \param StringRange some or all of the string to highlight.  This is
5247 /// templated so it can accept either a CharSourceRange or a SourceRange.
5248 ///
5249 /// \param FixIt optional fix it hint for the format string.
5250 template <typename Range>
5251 void CheckFormatHandler::EmitFormatDiagnostic(
5252     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5253     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5254     Range StringRange, ArrayRef<FixItHint> FixIt) {
5255   if (InFunctionCall) {
5256     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5257     D << StringRange;
5258     D << FixIt;
5259   } else {
5260     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5261       << ArgumentExpr->getSourceRange();
5262
5263     const Sema::SemaDiagnosticBuilder &Note =
5264       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5265              diag::note_format_string_defined);
5266
5267     Note << StringRange;
5268     Note << FixIt;
5269   }
5270 }
5271
5272 //===--- CHECK: Printf format string checking ------------------------------===//
5273
5274 namespace {
5275 class CheckPrintfHandler : public CheckFormatHandler {
5276 public:
5277   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5278                      const Expr *origFormatExpr,
5279                      const Sema::FormatStringType type, unsigned firstDataArg,
5280                      unsigned numDataArgs, bool isObjC, const char *beg,
5281                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5282                      unsigned formatIdx, bool inFunctionCall,
5283                      Sema::VariadicCallType CallType,
5284                      llvm::SmallBitVector &CheckedVarArgs,
5285                      UncoveredArgHandler &UncoveredArg)
5286       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5287                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5288                            inFunctionCall, CallType, CheckedVarArgs,
5289                            UncoveredArg) {}
5290
5291   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5292
5293   /// Returns true if '%@' specifiers are allowed in the format string.
5294   bool allowsObjCArg() const {
5295     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5296            FSType == Sema::FST_OSTrace;
5297   }
5298
5299   bool HandleInvalidPrintfConversionSpecifier(
5300                                       const analyze_printf::PrintfSpecifier &FS,
5301                                       const char *startSpecifier,
5302                                       unsigned specifierLen) override;
5303
5304   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5305                              const char *startSpecifier,
5306                              unsigned specifierLen) override;
5307   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5308                        const char *StartSpecifier,
5309                        unsigned SpecifierLen,
5310                        const Expr *E);
5311
5312   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5313                     const char *startSpecifier, unsigned specifierLen);
5314   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5315                            const analyze_printf::OptionalAmount &Amt,
5316                            unsigned type,
5317                            const char *startSpecifier, unsigned specifierLen);
5318   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5319                   const analyze_printf::OptionalFlag &flag,
5320                   const char *startSpecifier, unsigned specifierLen);
5321   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5322                          const analyze_printf::OptionalFlag &ignoredFlag,
5323                          const analyze_printf::OptionalFlag &flag,
5324                          const char *startSpecifier, unsigned specifierLen);
5325   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5326                            const Expr *E);
5327                            
5328   void HandleEmptyObjCModifierFlag(const char *startFlag,
5329                                    unsigned flagLen) override;
5330
5331   void HandleInvalidObjCModifierFlag(const char *startFlag,
5332                                             unsigned flagLen) override;
5333
5334   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5335                                            const char *flagsEnd,
5336                                            const char *conversionPosition) 
5337                                              override;
5338 };
5339 } // end anonymous namespace
5340
5341 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5342                                       const analyze_printf::PrintfSpecifier &FS,
5343                                       const char *startSpecifier,
5344                                       unsigned specifierLen) {
5345   const analyze_printf::PrintfConversionSpecifier &CS =
5346     FS.getConversionSpecifier();
5347   
5348   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5349                                           getLocationOfByte(CS.getStart()),
5350                                           startSpecifier, specifierLen,
5351                                           CS.getStart(), CS.getLength());
5352 }
5353
5354 bool CheckPrintfHandler::HandleAmount(
5355                                const analyze_format_string::OptionalAmount &Amt,
5356                                unsigned k, const char *startSpecifier,
5357                                unsigned specifierLen) {
5358   if (Amt.hasDataArgument()) {
5359     if (!HasVAListArg) {
5360       unsigned argIndex = Amt.getArgIndex();
5361       if (argIndex >= NumDataArgs) {
5362         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5363                                << k,
5364                              getLocationOfByte(Amt.getStart()),
5365                              /*IsStringLocation*/true,
5366                              getSpecifierRange(startSpecifier, specifierLen));
5367         // Don't do any more checking.  We will just emit
5368         // spurious errors.
5369         return false;
5370       }
5371
5372       // Type check the data argument.  It should be an 'int'.
5373       // Although not in conformance with C99, we also allow the argument to be
5374       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5375       // doesn't emit a warning for that case.
5376       CoveredArgs.set(argIndex);
5377       const Expr *Arg = getDataArg(argIndex);
5378       if (!Arg)
5379         return false;
5380
5381       QualType T = Arg->getType();
5382
5383       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5384       assert(AT.isValid());
5385
5386       if (!AT.matchesType(S.Context, T)) {
5387         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5388                                << k << AT.getRepresentativeTypeName(S.Context)
5389                                << T << Arg->getSourceRange(),
5390                              getLocationOfByte(Amt.getStart()),
5391                              /*IsStringLocation*/true,
5392                              getSpecifierRange(startSpecifier, specifierLen));
5393         // Don't do any more checking.  We will just emit
5394         // spurious errors.
5395         return false;
5396       }
5397     }
5398   }
5399   return true;
5400 }
5401
5402 void CheckPrintfHandler::HandleInvalidAmount(
5403                                       const analyze_printf::PrintfSpecifier &FS,
5404                                       const analyze_printf::OptionalAmount &Amt,
5405                                       unsigned type,
5406                                       const char *startSpecifier,
5407                                       unsigned specifierLen) {
5408   const analyze_printf::PrintfConversionSpecifier &CS =
5409     FS.getConversionSpecifier();
5410
5411   FixItHint fixit =
5412     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5413       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5414                                  Amt.getConstantLength()))
5415       : FixItHint();
5416
5417   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5418                          << type << CS.toString(),
5419                        getLocationOfByte(Amt.getStart()),
5420                        /*IsStringLocation*/true,
5421                        getSpecifierRange(startSpecifier, specifierLen),
5422                        fixit);
5423 }
5424
5425 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5426                                     const analyze_printf::OptionalFlag &flag,
5427                                     const char *startSpecifier,
5428                                     unsigned specifierLen) {
5429   // Warn about pointless flag with a fixit removal.
5430   const analyze_printf::PrintfConversionSpecifier &CS =
5431     FS.getConversionSpecifier();
5432   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5433                          << flag.toString() << CS.toString(),
5434                        getLocationOfByte(flag.getPosition()),
5435                        /*IsStringLocation*/true,
5436                        getSpecifierRange(startSpecifier, specifierLen),
5437                        FixItHint::CreateRemoval(
5438                          getSpecifierRange(flag.getPosition(), 1)));
5439 }
5440
5441 void CheckPrintfHandler::HandleIgnoredFlag(
5442                                 const analyze_printf::PrintfSpecifier &FS,
5443                                 const analyze_printf::OptionalFlag &ignoredFlag,
5444                                 const analyze_printf::OptionalFlag &flag,
5445                                 const char *startSpecifier,
5446                                 unsigned specifierLen) {
5447   // Warn about ignored flag with a fixit removal.
5448   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5449                          << ignoredFlag.toString() << flag.toString(),
5450                        getLocationOfByte(ignoredFlag.getPosition()),
5451                        /*IsStringLocation*/true,
5452                        getSpecifierRange(startSpecifier, specifierLen),
5453                        FixItHint::CreateRemoval(
5454                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5455 }
5456
5457 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5458 //                            bool IsStringLocation, Range StringRange,
5459 //                            ArrayRef<FixItHint> Fixit = None);
5460                             
5461 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5462                                                      unsigned flagLen) {
5463   // Warn about an empty flag.
5464   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5465                        getLocationOfByte(startFlag),
5466                        /*IsStringLocation*/true,
5467                        getSpecifierRange(startFlag, flagLen));
5468 }
5469
5470 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5471                                                        unsigned flagLen) {
5472   // Warn about an invalid flag.
5473   auto Range = getSpecifierRange(startFlag, flagLen);
5474   StringRef flag(startFlag, flagLen);
5475   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5476                       getLocationOfByte(startFlag),
5477                       /*IsStringLocation*/true,
5478                       Range, FixItHint::CreateRemoval(Range));
5479 }
5480
5481 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5482     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5483     // Warn about using '[...]' without a '@' conversion.
5484     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5485     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5486     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5487                          getLocationOfByte(conversionPosition),
5488                          /*IsStringLocation*/true,
5489                          Range, FixItHint::CreateRemoval(Range));
5490 }
5491
5492 // Determines if the specified is a C++ class or struct containing
5493 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5494 // "c_str()").
5495 template<typename MemberKind>
5496 static llvm::SmallPtrSet<MemberKind*, 1>
5497 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5498   const RecordType *RT = Ty->getAs<RecordType>();
5499   llvm::SmallPtrSet<MemberKind*, 1> Results;
5500
5501   if (!RT)
5502     return Results;
5503   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5504   if (!RD || !RD->getDefinition())
5505     return Results;
5506
5507   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5508                  Sema::LookupMemberName);
5509   R.suppressDiagnostics();
5510
5511   // We just need to include all members of the right kind turned up by the
5512   // filter, at this point.
5513   if (S.LookupQualifiedName(R, RT->getDecl()))
5514     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5515       NamedDecl *decl = (*I)->getUnderlyingDecl();
5516       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5517         Results.insert(FK);
5518     }
5519   return Results;
5520 }
5521
5522 /// Check if we could call '.c_str()' on an object.
5523 ///
5524 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5525 /// allow the call, or if it would be ambiguous).
5526 bool Sema::hasCStrMethod(const Expr *E) {
5527   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5528   MethodSet Results =
5529       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5530   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5531        MI != ME; ++MI)
5532     if ((*MI)->getMinRequiredArguments() == 0)
5533       return true;
5534   return false;
5535 }
5536
5537 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5538 // better diagnostic if so. AT is assumed to be valid.
5539 // Returns true when a c_str() conversion method is found.
5540 bool CheckPrintfHandler::checkForCStrMembers(
5541     const analyze_printf::ArgType &AT, const Expr *E) {
5542   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5543
5544   MethodSet Results =
5545       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5546
5547   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5548        MI != ME; ++MI) {
5549     const CXXMethodDecl *Method = *MI;
5550     if (Method->getMinRequiredArguments() == 0 &&
5551         AT.matchesType(S.Context, Method->getReturnType())) {
5552       // FIXME: Suggest parens if the expression needs them.
5553       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5554       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5555           << "c_str()"
5556           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5557       return true;
5558     }
5559   }
5560
5561   return false;
5562 }
5563
5564 bool
5565 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5566                                             &FS,
5567                                           const char *startSpecifier,
5568                                           unsigned specifierLen) {
5569   using namespace analyze_format_string;
5570   using namespace analyze_printf;  
5571   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5572
5573   if (FS.consumesDataArgument()) {
5574     if (atFirstArg) {
5575         atFirstArg = false;
5576         usesPositionalArgs = FS.usesPositionalArg();
5577     }
5578     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5579       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5580                                         startSpecifier, specifierLen);
5581       return false;
5582     }
5583   }
5584
5585   // First check if the field width, precision, and conversion specifier
5586   // have matching data arguments.
5587   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5588                     startSpecifier, specifierLen)) {
5589     return false;
5590   }
5591
5592   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5593                     startSpecifier, specifierLen)) {
5594     return false;
5595   }
5596
5597   if (!CS.consumesDataArgument()) {
5598     // FIXME: Technically specifying a precision or field width here
5599     // makes no sense.  Worth issuing a warning at some point.
5600     return true;
5601   }
5602
5603   // Consume the argument.
5604   unsigned argIndex = FS.getArgIndex();
5605   if (argIndex < NumDataArgs) {
5606     // The check to see if the argIndex is valid will come later.
5607     // We set the bit here because we may exit early from this
5608     // function if we encounter some other error.
5609     CoveredArgs.set(argIndex);
5610   }
5611
5612   // FreeBSD kernel extensions.
5613   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5614       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5615     // We need at least two arguments.
5616     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5617       return false;
5618
5619     // Claim the second argument.
5620     CoveredArgs.set(argIndex + 1);
5621
5622     // Type check the first argument (int for %b, pointer for %D)
5623     const Expr *Ex = getDataArg(argIndex);
5624     const analyze_printf::ArgType &AT =
5625       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5626         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5627     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5628       EmitFormatDiagnostic(
5629         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5630         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5631         << false << Ex->getSourceRange(),
5632         Ex->getLocStart(), /*IsStringLocation*/false,
5633         getSpecifierRange(startSpecifier, specifierLen));
5634
5635     // Type check the second argument (char * for both %b and %D)
5636     Ex = getDataArg(argIndex + 1);
5637     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5638     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5639       EmitFormatDiagnostic(
5640         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5641         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5642         << false << Ex->getSourceRange(),
5643         Ex->getLocStart(), /*IsStringLocation*/false,
5644         getSpecifierRange(startSpecifier, specifierLen));
5645
5646      return true;
5647   }
5648
5649   // Check for using an Objective-C specific conversion specifier
5650   // in a non-ObjC literal.
5651   if (!allowsObjCArg() && CS.isObjCArg()) {
5652     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5653                                                   specifierLen);
5654   }
5655
5656   // %P can only be used with os_log.
5657   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5658     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5659                                                   specifierLen);
5660   }
5661
5662   // %n is not allowed with os_log.
5663   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5664     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5665                          getLocationOfByte(CS.getStart()),
5666                          /*IsStringLocation*/ false,
5667                          getSpecifierRange(startSpecifier, specifierLen));
5668
5669     return true;
5670   }
5671
5672   // Only scalars are allowed for os_trace.
5673   if (FSType == Sema::FST_OSTrace &&
5674       (CS.getKind() == ConversionSpecifier::PArg ||
5675        CS.getKind() == ConversionSpecifier::sArg ||
5676        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5677     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5678                                                   specifierLen);
5679   }
5680
5681   // Check for use of public/private annotation outside of os_log().
5682   if (FSType != Sema::FST_OSLog) {
5683     if (FS.isPublic().isSet()) {
5684       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5685                                << "public",
5686                            getLocationOfByte(FS.isPublic().getPosition()),
5687                            /*IsStringLocation*/ false,
5688                            getSpecifierRange(startSpecifier, specifierLen));
5689     }
5690     if (FS.isPrivate().isSet()) {
5691       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5692                                << "private",
5693                            getLocationOfByte(FS.isPrivate().getPosition()),
5694                            /*IsStringLocation*/ false,
5695                            getSpecifierRange(startSpecifier, specifierLen));
5696     }
5697   }
5698
5699   // Check for invalid use of field width
5700   if (!FS.hasValidFieldWidth()) {
5701     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5702         startSpecifier, specifierLen);
5703   }
5704
5705   // Check for invalid use of precision
5706   if (!FS.hasValidPrecision()) {
5707     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5708         startSpecifier, specifierLen);
5709   }
5710
5711   // Precision is mandatory for %P specifier.
5712   if (CS.getKind() == ConversionSpecifier::PArg &&
5713       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5714     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5715                          getLocationOfByte(startSpecifier),
5716                          /*IsStringLocation*/ false,
5717                          getSpecifierRange(startSpecifier, specifierLen));
5718   }
5719
5720   // Check each flag does not conflict with any other component.
5721   if (!FS.hasValidThousandsGroupingPrefix())
5722     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5723   if (!FS.hasValidLeadingZeros())
5724     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5725   if (!FS.hasValidPlusPrefix())
5726     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5727   if (!FS.hasValidSpacePrefix())
5728     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5729   if (!FS.hasValidAlternativeForm())
5730     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5731   if (!FS.hasValidLeftJustified())
5732     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5733
5734   // Check that flags are not ignored by another flag
5735   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5736     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5737         startSpecifier, specifierLen);
5738   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5739     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5740             startSpecifier, specifierLen);
5741
5742   // Check the length modifier is valid with the given conversion specifier.
5743   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5744     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5745                                 diag::warn_format_nonsensical_length);
5746   else if (!FS.hasStandardLengthModifier())
5747     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5748   else if (!FS.hasStandardLengthConversionCombination())
5749     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5750                                 diag::warn_format_non_standard_conversion_spec);
5751
5752   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5753     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5754
5755   // The remaining checks depend on the data arguments.
5756   if (HasVAListArg)
5757     return true;
5758
5759   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5760     return false;
5761
5762   const Expr *Arg = getDataArg(argIndex);
5763   if (!Arg)
5764     return true;
5765
5766   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5767 }
5768
5769 static bool requiresParensToAddCast(const Expr *E) {
5770   // FIXME: We should have a general way to reason about operator
5771   // precedence and whether parens are actually needed here.
5772   // Take care of a few common cases where they aren't.
5773   const Expr *Inside = E->IgnoreImpCasts();
5774   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5775     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5776
5777   switch (Inside->getStmtClass()) {
5778   case Stmt::ArraySubscriptExprClass:
5779   case Stmt::CallExprClass:
5780   case Stmt::CharacterLiteralClass:
5781   case Stmt::CXXBoolLiteralExprClass:
5782   case Stmt::DeclRefExprClass:
5783   case Stmt::FloatingLiteralClass:
5784   case Stmt::IntegerLiteralClass:
5785   case Stmt::MemberExprClass:
5786   case Stmt::ObjCArrayLiteralClass:
5787   case Stmt::ObjCBoolLiteralExprClass:
5788   case Stmt::ObjCBoxedExprClass:
5789   case Stmt::ObjCDictionaryLiteralClass:
5790   case Stmt::ObjCEncodeExprClass:
5791   case Stmt::ObjCIvarRefExprClass:
5792   case Stmt::ObjCMessageExprClass:
5793   case Stmt::ObjCPropertyRefExprClass:
5794   case Stmt::ObjCStringLiteralClass:
5795   case Stmt::ObjCSubscriptRefExprClass:
5796   case Stmt::ParenExprClass:
5797   case Stmt::StringLiteralClass:
5798   case Stmt::UnaryOperatorClass:
5799     return false;
5800   default:
5801     return true;
5802   }
5803 }
5804
5805 static std::pair<QualType, StringRef>
5806 shouldNotPrintDirectly(const ASTContext &Context,
5807                        QualType IntendedTy,
5808                        const Expr *E) {
5809   // Use a 'while' to peel off layers of typedefs.
5810   QualType TyTy = IntendedTy;
5811   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5812     StringRef Name = UserTy->getDecl()->getName();
5813     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5814       .Case("NSInteger", Context.LongTy)
5815       .Case("NSUInteger", Context.UnsignedLongTy)
5816       .Case("SInt32", Context.IntTy)
5817       .Case("UInt32", Context.UnsignedIntTy)
5818       .Default(QualType());
5819
5820     if (!CastTy.isNull())
5821       return std::make_pair(CastTy, Name);
5822
5823     TyTy = UserTy->desugar();
5824   }
5825
5826   // Strip parens if necessary.
5827   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5828     return shouldNotPrintDirectly(Context,
5829                                   PE->getSubExpr()->getType(),
5830                                   PE->getSubExpr());
5831
5832   // If this is a conditional expression, then its result type is constructed
5833   // via usual arithmetic conversions and thus there might be no necessary
5834   // typedef sugar there.  Recurse to operands to check for NSInteger &
5835   // Co. usage condition.
5836   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5837     QualType TrueTy, FalseTy;
5838     StringRef TrueName, FalseName;
5839
5840     std::tie(TrueTy, TrueName) =
5841       shouldNotPrintDirectly(Context,
5842                              CO->getTrueExpr()->getType(),
5843                              CO->getTrueExpr());
5844     std::tie(FalseTy, FalseName) =
5845       shouldNotPrintDirectly(Context,
5846                              CO->getFalseExpr()->getType(),
5847                              CO->getFalseExpr());
5848
5849     if (TrueTy == FalseTy)
5850       return std::make_pair(TrueTy, TrueName);
5851     else if (TrueTy.isNull())
5852       return std::make_pair(FalseTy, FalseName);
5853     else if (FalseTy.isNull())
5854       return std::make_pair(TrueTy, TrueName);
5855   }
5856
5857   return std::make_pair(QualType(), StringRef());
5858 }
5859
5860 bool
5861 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5862                                     const char *StartSpecifier,
5863                                     unsigned SpecifierLen,
5864                                     const Expr *E) {
5865   using namespace analyze_format_string;
5866   using namespace analyze_printf;
5867   // Now type check the data expression that matches the
5868   // format specifier.
5869   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
5870   if (!AT.isValid())
5871     return true;
5872
5873   QualType ExprTy = E->getType();
5874   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5875     ExprTy = TET->getUnderlyingExpr()->getType();
5876   }
5877
5878   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5879
5880   if (match == analyze_printf::ArgType::Match) {
5881     return true;
5882   }
5883
5884   // Look through argument promotions for our error message's reported type.
5885   // This includes the integral and floating promotions, but excludes array
5886   // and function pointer decay; seeing that an argument intended to be a
5887   // string has type 'char [6]' is probably more confusing than 'char *'.
5888   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5889     if (ICE->getCastKind() == CK_IntegralCast ||
5890         ICE->getCastKind() == CK_FloatingCast) {
5891       E = ICE->getSubExpr();
5892       ExprTy = E->getType();
5893
5894       // Check if we didn't match because of an implicit cast from a 'char'
5895       // or 'short' to an 'int'.  This is done because printf is a varargs
5896       // function.
5897       if (ICE->getType() == S.Context.IntTy ||
5898           ICE->getType() == S.Context.UnsignedIntTy) {
5899         // All further checking is done on the subexpression.
5900         if (AT.matchesType(S.Context, ExprTy))
5901           return true;
5902       }
5903     }
5904   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5905     // Special case for 'a', which has type 'int' in C.
5906     // Note, however, that we do /not/ want to treat multibyte constants like
5907     // 'MooV' as characters! This form is deprecated but still exists.
5908     if (ExprTy == S.Context.IntTy)
5909       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5910         ExprTy = S.Context.CharTy;
5911   }
5912
5913   // Look through enums to their underlying type.
5914   bool IsEnum = false;
5915   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5916     ExprTy = EnumTy->getDecl()->getIntegerType();
5917     IsEnum = true;
5918   }
5919
5920   // %C in an Objective-C context prints a unichar, not a wchar_t.
5921   // If the argument is an integer of some kind, believe the %C and suggest
5922   // a cast instead of changing the conversion specifier.
5923   QualType IntendedTy = ExprTy;
5924   if (isObjCContext() &&
5925       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5926     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5927         !ExprTy->isCharType()) {
5928       // 'unichar' is defined as a typedef of unsigned short, but we should
5929       // prefer using the typedef if it is visible.
5930       IntendedTy = S.Context.UnsignedShortTy;
5931
5932       // While we are here, check if the value is an IntegerLiteral that happens
5933       // to be within the valid range.
5934       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5935         const llvm::APInt &V = IL->getValue();
5936         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5937           return true;
5938       }
5939
5940       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5941                           Sema::LookupOrdinaryName);
5942       if (S.LookupName(Result, S.getCurScope())) {
5943         NamedDecl *ND = Result.getFoundDecl();
5944         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5945           if (TD->getUnderlyingType() == IntendedTy)
5946             IntendedTy = S.Context.getTypedefType(TD);
5947       }
5948     }
5949   }
5950
5951   // Special-case some of Darwin's platform-independence types by suggesting
5952   // casts to primitive types that are known to be large enough.
5953   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5954   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5955     QualType CastTy;
5956     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5957     if (!CastTy.isNull()) {
5958       IntendedTy = CastTy;
5959       ShouldNotPrintDirectly = true;
5960     }
5961   }
5962
5963   // We may be able to offer a FixItHint if it is a supported type.
5964   PrintfSpecifier fixedFS = FS;
5965   bool success =
5966       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
5967
5968   if (success) {
5969     // Get the fix string from the fixed format specifier
5970     SmallString<16> buf;
5971     llvm::raw_svector_ostream os(buf);
5972     fixedFS.toString(os);
5973
5974     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5975
5976     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5977       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5978       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5979         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5980       }
5981       // In this case, the specifier is wrong and should be changed to match
5982       // the argument.
5983       EmitFormatDiagnostic(S.PDiag(diag)
5984                                << AT.getRepresentativeTypeName(S.Context)
5985                                << IntendedTy << IsEnum << E->getSourceRange(),
5986                            E->getLocStart(),
5987                            /*IsStringLocation*/ false, SpecRange,
5988                            FixItHint::CreateReplacement(SpecRange, os.str()));
5989     } else {
5990       // The canonical type for formatting this value is different from the
5991       // actual type of the expression. (This occurs, for example, with Darwin's
5992       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5993       // should be printed as 'long' for 64-bit compatibility.)
5994       // Rather than emitting a normal format/argument mismatch, we want to
5995       // add a cast to the recommended type (and correct the format string
5996       // if necessary).
5997       SmallString<16> CastBuf;
5998       llvm::raw_svector_ostream CastFix(CastBuf);
5999       CastFix << "(";
6000       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6001       CastFix << ")";
6002
6003       SmallVector<FixItHint,4> Hints;
6004       if (!AT.matchesType(S.Context, IntendedTy))
6005         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6006
6007       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6008         // If there's already a cast present, just replace it.
6009         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6010         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6011
6012       } else if (!requiresParensToAddCast(E)) {
6013         // If the expression has high enough precedence,
6014         // just write the C-style cast.
6015         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6016                                                    CastFix.str()));
6017       } else {
6018         // Otherwise, add parens around the expression as well as the cast.
6019         CastFix << "(";
6020         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6021                                                    CastFix.str()));
6022
6023         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6024         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6025       }
6026
6027       if (ShouldNotPrintDirectly) {
6028         // The expression has a type that should not be printed directly.
6029         // We extract the name from the typedef because we don't want to show
6030         // the underlying type in the diagnostic.
6031         StringRef Name;
6032         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6033           Name = TypedefTy->getDecl()->getName();
6034         else
6035           Name = CastTyName;
6036         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6037                                << Name << IntendedTy << IsEnum
6038                                << E->getSourceRange(),
6039                              E->getLocStart(), /*IsStringLocation=*/false,
6040                              SpecRange, Hints);
6041       } else {
6042         // In this case, the expression could be printed using a different
6043         // specifier, but we've decided that the specifier is probably correct 
6044         // and we should cast instead. Just use the normal warning message.
6045         EmitFormatDiagnostic(
6046           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6047             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6048             << E->getSourceRange(),
6049           E->getLocStart(), /*IsStringLocation*/false,
6050           SpecRange, Hints);
6051       }
6052     }
6053   } else {
6054     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6055                                                    SpecifierLen);
6056     // Since the warning for passing non-POD types to variadic functions
6057     // was deferred until now, we emit a warning for non-POD
6058     // arguments here.
6059     switch (S.isValidVarArgType(ExprTy)) {
6060     case Sema::VAK_Valid:
6061     case Sema::VAK_ValidInCXX11: {
6062       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6063       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6064         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6065       }
6066
6067       EmitFormatDiagnostic(
6068           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6069                         << IsEnum << CSR << E->getSourceRange(),
6070           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6071       break;
6072     }
6073     case Sema::VAK_Undefined:
6074     case Sema::VAK_MSVCUndefined:
6075       EmitFormatDiagnostic(
6076         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6077           << S.getLangOpts().CPlusPlus11
6078           << ExprTy
6079           << CallType
6080           << AT.getRepresentativeTypeName(S.Context)
6081           << CSR
6082           << E->getSourceRange(),
6083         E->getLocStart(), /*IsStringLocation*/false, CSR);
6084       checkForCStrMembers(AT, E);
6085       break;
6086
6087     case Sema::VAK_Invalid:
6088       if (ExprTy->isObjCObjectType())
6089         EmitFormatDiagnostic(
6090           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6091             << S.getLangOpts().CPlusPlus11
6092             << ExprTy
6093             << CallType
6094             << AT.getRepresentativeTypeName(S.Context)
6095             << CSR
6096             << E->getSourceRange(),
6097           E->getLocStart(), /*IsStringLocation*/false, CSR);
6098       else
6099         // FIXME: If this is an initializer list, suggest removing the braces
6100         // or inserting a cast to the target type.
6101         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6102           << isa<InitListExpr>(E) << ExprTy << CallType
6103           << AT.getRepresentativeTypeName(S.Context)
6104           << E->getSourceRange();
6105       break;
6106     }
6107
6108     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6109            "format string specifier index out of range");
6110     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6111   }
6112
6113   return true;
6114 }
6115
6116 //===--- CHECK: Scanf format string checking ------------------------------===//
6117
6118 namespace {  
6119 class CheckScanfHandler : public CheckFormatHandler {
6120 public:
6121   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6122                     const Expr *origFormatExpr, Sema::FormatStringType type,
6123                     unsigned firstDataArg, unsigned numDataArgs,
6124                     const char *beg, bool hasVAListArg,
6125                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6126                     bool inFunctionCall, Sema::VariadicCallType CallType,
6127                     llvm::SmallBitVector &CheckedVarArgs,
6128                     UncoveredArgHandler &UncoveredArg)
6129       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6130                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6131                            inFunctionCall, CallType, CheckedVarArgs,
6132                            UncoveredArg) {}
6133
6134   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6135                             const char *startSpecifier,
6136                             unsigned specifierLen) override;
6137   
6138   bool HandleInvalidScanfConversionSpecifier(
6139           const analyze_scanf::ScanfSpecifier &FS,
6140           const char *startSpecifier,
6141           unsigned specifierLen) override;
6142
6143   void HandleIncompleteScanList(const char *start, const char *end) override;
6144 };
6145 } // end anonymous namespace
6146
6147 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6148                                                  const char *end) {
6149   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6150                        getLocationOfByte(end), /*IsStringLocation*/true,
6151                        getSpecifierRange(start, end - start));
6152 }
6153
6154 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6155                                         const analyze_scanf::ScanfSpecifier &FS,
6156                                         const char *startSpecifier,
6157                                         unsigned specifierLen) {
6158
6159   const analyze_scanf::ScanfConversionSpecifier &CS =
6160     FS.getConversionSpecifier();
6161
6162   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6163                                           getLocationOfByte(CS.getStart()),
6164                                           startSpecifier, specifierLen,
6165                                           CS.getStart(), CS.getLength());
6166 }
6167
6168 bool CheckScanfHandler::HandleScanfSpecifier(
6169                                        const analyze_scanf::ScanfSpecifier &FS,
6170                                        const char *startSpecifier,
6171                                        unsigned specifierLen) {
6172   using namespace analyze_scanf;
6173   using namespace analyze_format_string;  
6174
6175   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6176
6177   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6178   // be used to decide if we are using positional arguments consistently.
6179   if (FS.consumesDataArgument()) {
6180     if (atFirstArg) {
6181       atFirstArg = false;
6182       usesPositionalArgs = FS.usesPositionalArg();
6183     }
6184     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6185       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6186                                         startSpecifier, specifierLen);
6187       return false;
6188     }
6189   }
6190   
6191   // Check if the field with is non-zero.
6192   const OptionalAmount &Amt = FS.getFieldWidth();
6193   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6194     if (Amt.getConstantAmount() == 0) {
6195       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6196                                                    Amt.getConstantLength());
6197       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6198                            getLocationOfByte(Amt.getStart()),
6199                            /*IsStringLocation*/true, R,
6200                            FixItHint::CreateRemoval(R));
6201     }
6202   }
6203
6204   if (!FS.consumesDataArgument()) {
6205     // FIXME: Technically specifying a precision or field width here
6206     // makes no sense.  Worth issuing a warning at some point.
6207     return true;
6208   }
6209
6210   // Consume the argument.
6211   unsigned argIndex = FS.getArgIndex();
6212   if (argIndex < NumDataArgs) {
6213       // The check to see if the argIndex is valid will come later.
6214       // We set the bit here because we may exit early from this
6215       // function if we encounter some other error.
6216     CoveredArgs.set(argIndex);
6217   }
6218
6219   // Check the length modifier is valid with the given conversion specifier.
6220   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6221     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6222                                 diag::warn_format_nonsensical_length);
6223   else if (!FS.hasStandardLengthModifier())
6224     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6225   else if (!FS.hasStandardLengthConversionCombination())
6226     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6227                                 diag::warn_format_non_standard_conversion_spec);
6228
6229   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6230     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6231
6232   // The remaining checks depend on the data arguments.
6233   if (HasVAListArg)
6234     return true;
6235
6236   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6237     return false;
6238
6239   // Check that the argument type matches the format specifier.
6240   const Expr *Ex = getDataArg(argIndex);
6241   if (!Ex)
6242     return true;
6243
6244   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6245
6246   if (!AT.isValid()) {
6247     return true;
6248   }
6249
6250   analyze_format_string::ArgType::MatchKind match =
6251       AT.matchesType(S.Context, Ex->getType());
6252   if (match == analyze_format_string::ArgType::Match) {
6253     return true;
6254   }
6255
6256   ScanfSpecifier fixedFS = FS;
6257   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6258                                  S.getLangOpts(), S.Context);
6259
6260   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6261   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6262     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6263   }
6264
6265   if (success) {
6266     // Get the fix string from the fixed format specifier.
6267     SmallString<128> buf;
6268     llvm::raw_svector_ostream os(buf);
6269     fixedFS.toString(os);
6270
6271     EmitFormatDiagnostic(
6272         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6273                       << Ex->getType() << false << Ex->getSourceRange(),
6274         Ex->getLocStart(),
6275         /*IsStringLocation*/ false,
6276         getSpecifierRange(startSpecifier, specifierLen),
6277         FixItHint::CreateReplacement(
6278             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6279   } else {
6280     EmitFormatDiagnostic(S.PDiag(diag)
6281                              << AT.getRepresentativeTypeName(S.Context)
6282                              << Ex->getType() << false << Ex->getSourceRange(),
6283                          Ex->getLocStart(),
6284                          /*IsStringLocation*/ false,
6285                          getSpecifierRange(startSpecifier, specifierLen));
6286   }
6287
6288   return true;
6289 }
6290
6291 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6292                               const Expr *OrigFormatExpr,
6293                               ArrayRef<const Expr *> Args,
6294                               bool HasVAListArg, unsigned format_idx,
6295                               unsigned firstDataArg,
6296                               Sema::FormatStringType Type,
6297                               bool inFunctionCall,
6298                               Sema::VariadicCallType CallType,
6299                               llvm::SmallBitVector &CheckedVarArgs,
6300                               UncoveredArgHandler &UncoveredArg) {
6301   // CHECK: is the format string a wide literal?
6302   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6303     CheckFormatHandler::EmitFormatDiagnostic(
6304       S, inFunctionCall, Args[format_idx],
6305       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6306       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6307     return;
6308   }
6309
6310   // Str - The format string.  NOTE: this is NOT null-terminated!
6311   StringRef StrRef = FExpr->getString();
6312   const char *Str = StrRef.data();
6313   // Account for cases where the string literal is truncated in a declaration.
6314   const ConstantArrayType *T =
6315     S.Context.getAsConstantArrayType(FExpr->getType());
6316   assert(T && "String literal not of constant array type!");
6317   size_t TypeSize = T->getSize().getZExtValue();
6318   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6319   const unsigned numDataArgs = Args.size() - firstDataArg;
6320
6321   // Emit a warning if the string literal is truncated and does not contain an
6322   // embedded null character.
6323   if (TypeSize <= StrRef.size() &&
6324       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6325     CheckFormatHandler::EmitFormatDiagnostic(
6326         S, inFunctionCall, Args[format_idx],
6327         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6328         FExpr->getLocStart(),
6329         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6330     return;
6331   }
6332
6333   // CHECK: empty format string?
6334   if (StrLen == 0 && numDataArgs > 0) {
6335     CheckFormatHandler::EmitFormatDiagnostic(
6336       S, inFunctionCall, Args[format_idx],
6337       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6338       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6339     return;
6340   }
6341
6342   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6343       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6344       Type == Sema::FST_OSTrace) {
6345     CheckPrintfHandler H(
6346         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6347         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6348         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6349         CheckedVarArgs, UncoveredArg);
6350
6351     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6352                                                   S.getLangOpts(),
6353                                                   S.Context.getTargetInfo(),
6354                                             Type == Sema::FST_FreeBSDKPrintf))
6355       H.DoneProcessing();
6356   } else if (Type == Sema::FST_Scanf) {
6357     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6358                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6359                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6360
6361     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6362                                                  S.getLangOpts(),
6363                                                  S.Context.getTargetInfo()))
6364       H.DoneProcessing();
6365   } // TODO: handle other formats
6366 }
6367
6368 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6369   // Str - The format string.  NOTE: this is NOT null-terminated!
6370   StringRef StrRef = FExpr->getString();
6371   const char *Str = StrRef.data();
6372   // Account for cases where the string literal is truncated in a declaration.
6373   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6374   assert(T && "String literal not of constant array type!");
6375   size_t TypeSize = T->getSize().getZExtValue();
6376   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6377   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6378                                                          getLangOpts(),
6379                                                          Context.getTargetInfo());
6380 }
6381
6382 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6383
6384 // Returns the related absolute value function that is larger, of 0 if one
6385 // does not exist.
6386 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6387   switch (AbsFunction) {
6388   default:
6389     return 0;
6390
6391   case Builtin::BI__builtin_abs:
6392     return Builtin::BI__builtin_labs;
6393   case Builtin::BI__builtin_labs:
6394     return Builtin::BI__builtin_llabs;
6395   case Builtin::BI__builtin_llabs:
6396     return 0;
6397
6398   case Builtin::BI__builtin_fabsf:
6399     return Builtin::BI__builtin_fabs;
6400   case Builtin::BI__builtin_fabs:
6401     return Builtin::BI__builtin_fabsl;
6402   case Builtin::BI__builtin_fabsl:
6403     return 0;
6404
6405   case Builtin::BI__builtin_cabsf:
6406     return Builtin::BI__builtin_cabs;
6407   case Builtin::BI__builtin_cabs:
6408     return Builtin::BI__builtin_cabsl;
6409   case Builtin::BI__builtin_cabsl:
6410     return 0;
6411
6412   case Builtin::BIabs:
6413     return Builtin::BIlabs;
6414   case Builtin::BIlabs:
6415     return Builtin::BIllabs;
6416   case Builtin::BIllabs:
6417     return 0;
6418
6419   case Builtin::BIfabsf:
6420     return Builtin::BIfabs;
6421   case Builtin::BIfabs:
6422     return Builtin::BIfabsl;
6423   case Builtin::BIfabsl:
6424     return 0;
6425
6426   case Builtin::BIcabsf:
6427    return Builtin::BIcabs;
6428   case Builtin::BIcabs:
6429     return Builtin::BIcabsl;
6430   case Builtin::BIcabsl:
6431     return 0;
6432   }
6433 }
6434
6435 // Returns the argument type of the absolute value function.
6436 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6437                                              unsigned AbsType) {
6438   if (AbsType == 0)
6439     return QualType();
6440
6441   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6442   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6443   if (Error != ASTContext::GE_None)
6444     return QualType();
6445
6446   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6447   if (!FT)
6448     return QualType();
6449
6450   if (FT->getNumParams() != 1)
6451     return QualType();
6452
6453   return FT->getParamType(0);
6454 }
6455
6456 // Returns the best absolute value function, or zero, based on type and
6457 // current absolute value function.
6458 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6459                                    unsigned AbsFunctionKind) {
6460   unsigned BestKind = 0;
6461   uint64_t ArgSize = Context.getTypeSize(ArgType);
6462   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6463        Kind = getLargerAbsoluteValueFunction(Kind)) {
6464     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6465     if (Context.getTypeSize(ParamType) >= ArgSize) {
6466       if (BestKind == 0)
6467         BestKind = Kind;
6468       else if (Context.hasSameType(ParamType, ArgType)) {
6469         BestKind = Kind;
6470         break;
6471       }
6472     }
6473   }
6474   return BestKind;
6475 }
6476
6477 enum AbsoluteValueKind {
6478   AVK_Integer,
6479   AVK_Floating,
6480   AVK_Complex
6481 };
6482
6483 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6484   if (T->isIntegralOrEnumerationType())
6485     return AVK_Integer;
6486   if (T->isRealFloatingType())
6487     return AVK_Floating;
6488   if (T->isAnyComplexType())
6489     return AVK_Complex;
6490
6491   llvm_unreachable("Type not integer, floating, or complex");
6492 }
6493
6494 // Changes the absolute value function to a different type.  Preserves whether
6495 // the function is a builtin.
6496 static unsigned changeAbsFunction(unsigned AbsKind,
6497                                   AbsoluteValueKind ValueKind) {
6498   switch (ValueKind) {
6499   case AVK_Integer:
6500     switch (AbsKind) {
6501     default:
6502       return 0;
6503     case Builtin::BI__builtin_fabsf:
6504     case Builtin::BI__builtin_fabs:
6505     case Builtin::BI__builtin_fabsl:
6506     case Builtin::BI__builtin_cabsf:
6507     case Builtin::BI__builtin_cabs:
6508     case Builtin::BI__builtin_cabsl:
6509       return Builtin::BI__builtin_abs;
6510     case Builtin::BIfabsf:
6511     case Builtin::BIfabs:
6512     case Builtin::BIfabsl:
6513     case Builtin::BIcabsf:
6514     case Builtin::BIcabs:
6515     case Builtin::BIcabsl:
6516       return Builtin::BIabs;
6517     }
6518   case AVK_Floating:
6519     switch (AbsKind) {
6520     default:
6521       return 0;
6522     case Builtin::BI__builtin_abs:
6523     case Builtin::BI__builtin_labs:
6524     case Builtin::BI__builtin_llabs:
6525     case Builtin::BI__builtin_cabsf:
6526     case Builtin::BI__builtin_cabs:
6527     case Builtin::BI__builtin_cabsl:
6528       return Builtin::BI__builtin_fabsf;
6529     case Builtin::BIabs:
6530     case Builtin::BIlabs:
6531     case Builtin::BIllabs:
6532     case Builtin::BIcabsf:
6533     case Builtin::BIcabs:
6534     case Builtin::BIcabsl:
6535       return Builtin::BIfabsf;
6536     }
6537   case AVK_Complex:
6538     switch (AbsKind) {
6539     default:
6540       return 0;
6541     case Builtin::BI__builtin_abs:
6542     case Builtin::BI__builtin_labs:
6543     case Builtin::BI__builtin_llabs:
6544     case Builtin::BI__builtin_fabsf:
6545     case Builtin::BI__builtin_fabs:
6546     case Builtin::BI__builtin_fabsl:
6547       return Builtin::BI__builtin_cabsf;
6548     case Builtin::BIabs:
6549     case Builtin::BIlabs:
6550     case Builtin::BIllabs:
6551     case Builtin::BIfabsf:
6552     case Builtin::BIfabs:
6553     case Builtin::BIfabsl:
6554       return Builtin::BIcabsf;
6555     }
6556   }
6557   llvm_unreachable("Unable to convert function");
6558 }
6559
6560 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6561   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6562   if (!FnInfo)
6563     return 0;
6564
6565   switch (FDecl->getBuiltinID()) {
6566   default:
6567     return 0;
6568   case Builtin::BI__builtin_abs:
6569   case Builtin::BI__builtin_fabs:
6570   case Builtin::BI__builtin_fabsf:
6571   case Builtin::BI__builtin_fabsl:
6572   case Builtin::BI__builtin_labs:
6573   case Builtin::BI__builtin_llabs:
6574   case Builtin::BI__builtin_cabs:
6575   case Builtin::BI__builtin_cabsf:
6576   case Builtin::BI__builtin_cabsl:
6577   case Builtin::BIabs:
6578   case Builtin::BIlabs:
6579   case Builtin::BIllabs:
6580   case Builtin::BIfabs:
6581   case Builtin::BIfabsf:
6582   case Builtin::BIfabsl:
6583   case Builtin::BIcabs:
6584   case Builtin::BIcabsf:
6585   case Builtin::BIcabsl:
6586     return FDecl->getBuiltinID();
6587   }
6588   llvm_unreachable("Unknown Builtin type");
6589 }
6590
6591 // If the replacement is valid, emit a note with replacement function.
6592 // Additionally, suggest including the proper header if not already included.
6593 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6594                             unsigned AbsKind, QualType ArgType) {
6595   bool EmitHeaderHint = true;
6596   const char *HeaderName = nullptr;
6597   const char *FunctionName = nullptr;
6598   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6599     FunctionName = "std::abs";
6600     if (ArgType->isIntegralOrEnumerationType()) {
6601       HeaderName = "cstdlib";
6602     } else if (ArgType->isRealFloatingType()) {
6603       HeaderName = "cmath";
6604     } else {
6605       llvm_unreachable("Invalid Type");
6606     }
6607
6608     // Lookup all std::abs
6609     if (NamespaceDecl *Std = S.getStdNamespace()) {
6610       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6611       R.suppressDiagnostics();
6612       S.LookupQualifiedName(R, Std);
6613
6614       for (const auto *I : R) {
6615         const FunctionDecl *FDecl = nullptr;
6616         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6617           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6618         } else {
6619           FDecl = dyn_cast<FunctionDecl>(I);
6620         }
6621         if (!FDecl)
6622           continue;
6623
6624         // Found std::abs(), check that they are the right ones.
6625         if (FDecl->getNumParams() != 1)
6626           continue;
6627
6628         // Check that the parameter type can handle the argument.
6629         QualType ParamType = FDecl->getParamDecl(0)->getType();
6630         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6631             S.Context.getTypeSize(ArgType) <=
6632                 S.Context.getTypeSize(ParamType)) {
6633           // Found a function, don't need the header hint.
6634           EmitHeaderHint = false;
6635           break;
6636         }
6637       }
6638     }
6639   } else {
6640     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6641     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6642
6643     if (HeaderName) {
6644       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6645       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6646       R.suppressDiagnostics();
6647       S.LookupName(R, S.getCurScope());
6648
6649       if (R.isSingleResult()) {
6650         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6651         if (FD && FD->getBuiltinID() == AbsKind) {
6652           EmitHeaderHint = false;
6653         } else {
6654           return;
6655         }
6656       } else if (!R.empty()) {
6657         return;
6658       }
6659     }
6660   }
6661
6662   S.Diag(Loc, diag::note_replace_abs_function)
6663       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6664
6665   if (!HeaderName)
6666     return;
6667
6668   if (!EmitHeaderHint)
6669     return;
6670
6671   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6672                                                     << FunctionName;
6673 }
6674
6675 template <std::size_t StrLen>
6676 static bool IsStdFunction(const FunctionDecl *FDecl,
6677                           const char (&Str)[StrLen]) {
6678   if (!FDecl)
6679     return false;
6680   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6681     return false;
6682   if (!FDecl->isInStdNamespace())
6683     return false;
6684
6685   return true;
6686 }
6687
6688 // Warn when using the wrong abs() function.
6689 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6690                                       const FunctionDecl *FDecl) {
6691   if (Call->getNumArgs() != 1)
6692     return;
6693
6694   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6695   bool IsStdAbs = IsStdFunction(FDecl, "abs");
6696   if (AbsKind == 0 && !IsStdAbs)
6697     return;
6698
6699   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6700   QualType ParamType = Call->getArg(0)->getType();
6701
6702   // Unsigned types cannot be negative.  Suggest removing the absolute value
6703   // function call.
6704   if (ArgType->isUnsignedIntegerType()) {
6705     const char *FunctionName =
6706         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6707     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6708     Diag(Call->getExprLoc(), diag::note_remove_abs)
6709         << FunctionName
6710         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6711     return;
6712   }
6713
6714   // Taking the absolute value of a pointer is very suspicious, they probably
6715   // wanted to index into an array, dereference a pointer, call a function, etc.
6716   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6717     unsigned DiagType = 0;
6718     if (ArgType->isFunctionType())
6719       DiagType = 1;
6720     else if (ArgType->isArrayType())
6721       DiagType = 2;
6722
6723     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6724     return;
6725   }
6726
6727   // std::abs has overloads which prevent most of the absolute value problems
6728   // from occurring.
6729   if (IsStdAbs)
6730     return;
6731
6732   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6733   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6734
6735   // The argument and parameter are the same kind.  Check if they are the right
6736   // size.
6737   if (ArgValueKind == ParamValueKind) {
6738     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6739       return;
6740
6741     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6742     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6743         << FDecl << ArgType << ParamType;
6744
6745     if (NewAbsKind == 0)
6746       return;
6747
6748     emitReplacement(*this, Call->getExprLoc(),
6749                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6750     return;
6751   }
6752
6753   // ArgValueKind != ParamValueKind
6754   // The wrong type of absolute value function was used.  Attempt to find the
6755   // proper one.
6756   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6757   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6758   if (NewAbsKind == 0)
6759     return;
6760
6761   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6762       << FDecl << ParamValueKind << ArgValueKind;
6763
6764   emitReplacement(*this, Call->getExprLoc(),
6765                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6766 }
6767
6768 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6769 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6770                                 const FunctionDecl *FDecl) {
6771   if (!Call || !FDecl) return;
6772
6773   // Ignore template specializations and macros.
6774   if (!ActiveTemplateInstantiations.empty()) return;
6775   if (Call->getExprLoc().isMacroID()) return;
6776
6777   // Only care about the one template argument, two function parameter std::max
6778   if (Call->getNumArgs() != 2) return;
6779   if (!IsStdFunction(FDecl, "max")) return;
6780   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6781   if (!ArgList) return;
6782   if (ArgList->size() != 1) return;
6783
6784   // Check that template type argument is unsigned integer.
6785   const auto& TA = ArgList->get(0);
6786   if (TA.getKind() != TemplateArgument::Type) return;
6787   QualType ArgType = TA.getAsType();
6788   if (!ArgType->isUnsignedIntegerType()) return;
6789
6790   // See if either argument is a literal zero.
6791   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6792     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6793     if (!MTE) return false;
6794     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6795     if (!Num) return false;
6796     if (Num->getValue() != 0) return false;
6797     return true;
6798   };
6799
6800   const Expr *FirstArg = Call->getArg(0);
6801   const Expr *SecondArg = Call->getArg(1);
6802   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6803   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6804
6805   // Only warn when exactly one argument is zero.
6806   if (IsFirstArgZero == IsSecondArgZero) return;
6807
6808   SourceRange FirstRange = FirstArg->getSourceRange();
6809   SourceRange SecondRange = SecondArg->getSourceRange();
6810
6811   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6812
6813   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6814       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6815
6816   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6817   SourceRange RemovalRange;
6818   if (IsFirstArgZero) {
6819     RemovalRange = SourceRange(FirstRange.getBegin(),
6820                                SecondRange.getBegin().getLocWithOffset(-1));
6821   } else {
6822     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6823                                SecondRange.getEnd());
6824   }
6825
6826   Diag(Call->getExprLoc(), diag::note_remove_max_call)
6827         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6828         << FixItHint::CreateRemoval(RemovalRange);
6829 }
6830
6831 //===--- CHECK: Standard memory functions ---------------------------------===//
6832
6833 /// \brief Takes the expression passed to the size_t parameter of functions
6834 /// such as memcmp, strncat, etc and warns if it's a comparison.
6835 ///
6836 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6837 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6838                                            IdentifierInfo *FnName,
6839                                            SourceLocation FnLoc,
6840                                            SourceLocation RParenLoc) {
6841   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6842   if (!Size)
6843     return false;
6844
6845   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6846   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6847     return false;
6848
6849   SourceRange SizeRange = Size->getSourceRange();
6850   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6851       << SizeRange << FnName;
6852   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6853       << FnName << FixItHint::CreateInsertion(
6854                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6855       << FixItHint::CreateRemoval(RParenLoc);
6856   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6857       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6858       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6859                                     ")");
6860
6861   return true;
6862 }
6863
6864 /// \brief Determine whether the given type is or contains a dynamic class type
6865 /// (e.g., whether it has a vtable).
6866 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6867                                                      bool &IsContained) {
6868   // Look through array types while ignoring qualifiers.
6869   const Type *Ty = T->getBaseElementTypeUnsafe();
6870   IsContained = false;
6871
6872   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6873   RD = RD ? RD->getDefinition() : nullptr;
6874   if (!RD || RD->isInvalidDecl())
6875     return nullptr;
6876
6877   if (RD->isDynamicClass())
6878     return RD;
6879
6880   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6881   // It's impossible for a class to transitively contain itself by value, so
6882   // infinite recursion is impossible.
6883   for (auto *FD : RD->fields()) {
6884     bool SubContained;
6885     if (const CXXRecordDecl *ContainedRD =
6886             getContainedDynamicClass(FD->getType(), SubContained)) {
6887       IsContained = true;
6888       return ContainedRD;
6889     }
6890   }
6891
6892   return nullptr;
6893 }
6894
6895 /// \brief If E is a sizeof expression, returns its argument expression,
6896 /// otherwise returns NULL.
6897 static const Expr *getSizeOfExprArg(const Expr *E) {
6898   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6899       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6900     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6901       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6902
6903   return nullptr;
6904 }
6905
6906 /// \brief If E is a sizeof expression, returns its argument type.
6907 static QualType getSizeOfArgType(const Expr *E) {
6908   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6909       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6910     if (SizeOf->getKind() == clang::UETT_SizeOf)
6911       return SizeOf->getTypeOfArgument();
6912
6913   return QualType();
6914 }
6915
6916 /// \brief Check for dangerous or invalid arguments to memset().
6917 ///
6918 /// This issues warnings on known problematic, dangerous or unspecified
6919 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6920 /// function calls.
6921 ///
6922 /// \param Call The call expression to diagnose.
6923 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6924                                    unsigned BId,
6925                                    IdentifierInfo *FnName) {
6926   assert(BId != 0);
6927
6928   // It is possible to have a non-standard definition of memset.  Validate
6929   // we have enough arguments, and if not, abort further checking.
6930   unsigned ExpectedNumArgs =
6931       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6932   if (Call->getNumArgs() < ExpectedNumArgs)
6933     return;
6934
6935   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6936                       BId == Builtin::BIstrndup ? 1 : 2);
6937   unsigned LenArg =
6938       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6939   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6940
6941   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6942                                      Call->getLocStart(), Call->getRParenLoc()))
6943     return;
6944
6945   // We have special checking when the length is a sizeof expression.
6946   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6947   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6948   llvm::FoldingSetNodeID SizeOfArgID;
6949
6950   // Although widely used, 'bzero' is not a standard function. Be more strict
6951   // with the argument types before allowing diagnostics and only allow the
6952   // form bzero(ptr, sizeof(...)).
6953   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6954   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6955     return;
6956
6957   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6958     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6959     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6960
6961     QualType DestTy = Dest->getType();
6962     QualType PointeeTy;
6963     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6964       PointeeTy = DestPtrTy->getPointeeType();
6965
6966       // Never warn about void type pointers. This can be used to suppress
6967       // false positives.
6968       if (PointeeTy->isVoidType())
6969         continue;
6970
6971       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6972       // actually comparing the expressions for equality. Because computing the
6973       // expression IDs can be expensive, we only do this if the diagnostic is
6974       // enabled.
6975       if (SizeOfArg &&
6976           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6977                            SizeOfArg->getExprLoc())) {
6978         // We only compute IDs for expressions if the warning is enabled, and
6979         // cache the sizeof arg's ID.
6980         if (SizeOfArgID == llvm::FoldingSetNodeID())
6981           SizeOfArg->Profile(SizeOfArgID, Context, true);
6982         llvm::FoldingSetNodeID DestID;
6983         Dest->Profile(DestID, Context, true);
6984         if (DestID == SizeOfArgID) {
6985           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6986           //       over sizeof(src) as well.
6987           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6988           StringRef ReadableName = FnName->getName();
6989
6990           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6991             if (UnaryOp->getOpcode() == UO_AddrOf)
6992               ActionIdx = 1; // If its an address-of operator, just remove it.
6993           if (!PointeeTy->isIncompleteType() &&
6994               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6995             ActionIdx = 2; // If the pointee's size is sizeof(char),
6996                            // suggest an explicit length.
6997
6998           // If the function is defined as a builtin macro, do not show macro
6999           // expansion.
7000           SourceLocation SL = SizeOfArg->getExprLoc();
7001           SourceRange DSR = Dest->getSourceRange();
7002           SourceRange SSR = SizeOfArg->getSourceRange();
7003           SourceManager &SM = getSourceManager();
7004
7005           if (SM.isMacroArgExpansion(SL)) {
7006             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7007             SL = SM.getSpellingLoc(SL);
7008             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7009                              SM.getSpellingLoc(DSR.getEnd()));
7010             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7011                              SM.getSpellingLoc(SSR.getEnd()));
7012           }
7013
7014           DiagRuntimeBehavior(SL, SizeOfArg,
7015                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7016                                 << ReadableName
7017                                 << PointeeTy
7018                                 << DestTy
7019                                 << DSR
7020                                 << SSR);
7021           DiagRuntimeBehavior(SL, SizeOfArg,
7022                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7023                                 << ActionIdx
7024                                 << SSR);
7025
7026           break;
7027         }
7028       }
7029
7030       // Also check for cases where the sizeof argument is the exact same
7031       // type as the memory argument, and where it points to a user-defined
7032       // record type.
7033       if (SizeOfArgTy != QualType()) {
7034         if (PointeeTy->isRecordType() &&
7035             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7036           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7037                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7038                                 << FnName << SizeOfArgTy << ArgIdx
7039                                 << PointeeTy << Dest->getSourceRange()
7040                                 << LenExpr->getSourceRange());
7041           break;
7042         }
7043       }
7044     } else if (DestTy->isArrayType()) {
7045       PointeeTy = DestTy;
7046     }
7047
7048     if (PointeeTy == QualType())
7049       continue;
7050
7051     // Always complain about dynamic classes.
7052     bool IsContained;
7053     if (const CXXRecordDecl *ContainedRD =
7054             getContainedDynamicClass(PointeeTy, IsContained)) {
7055
7056       unsigned OperationType = 0;
7057       // "overwritten" if we're warning about the destination for any call
7058       // but memcmp; otherwise a verb appropriate to the call.
7059       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7060         if (BId == Builtin::BImemcpy)
7061           OperationType = 1;
7062         else if(BId == Builtin::BImemmove)
7063           OperationType = 2;
7064         else if (BId == Builtin::BImemcmp)
7065           OperationType = 3;
7066       }
7067         
7068       DiagRuntimeBehavior(
7069         Dest->getExprLoc(), Dest,
7070         PDiag(diag::warn_dyn_class_memaccess)
7071           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7072           << FnName << IsContained << ContainedRD << OperationType
7073           << Call->getCallee()->getSourceRange());
7074     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7075              BId != Builtin::BImemset)
7076       DiagRuntimeBehavior(
7077         Dest->getExprLoc(), Dest,
7078         PDiag(diag::warn_arc_object_memaccess)
7079           << ArgIdx << FnName << PointeeTy
7080           << Call->getCallee()->getSourceRange());
7081     else
7082       continue;
7083
7084     DiagRuntimeBehavior(
7085       Dest->getExprLoc(), Dest,
7086       PDiag(diag::note_bad_memaccess_silence)
7087         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7088     break;
7089   }
7090 }
7091
7092 // A little helper routine: ignore addition and subtraction of integer literals.
7093 // This intentionally does not ignore all integer constant expressions because
7094 // we don't want to remove sizeof().
7095 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7096   Ex = Ex->IgnoreParenCasts();
7097
7098   for (;;) {
7099     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7100     if (!BO || !BO->isAdditiveOp())
7101       break;
7102
7103     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7104     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7105     
7106     if (isa<IntegerLiteral>(RHS))
7107       Ex = LHS;
7108     else if (isa<IntegerLiteral>(LHS))
7109       Ex = RHS;
7110     else
7111       break;
7112   }
7113
7114   return Ex;
7115 }
7116
7117 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7118                                                       ASTContext &Context) {
7119   // Only handle constant-sized or VLAs, but not flexible members.
7120   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7121     // Only issue the FIXIT for arrays of size > 1.
7122     if (CAT->getSize().getSExtValue() <= 1)
7123       return false;
7124   } else if (!Ty->isVariableArrayType()) {
7125     return false;
7126   }
7127   return true;
7128 }
7129
7130 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7131 // be the size of the source, instead of the destination.
7132 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7133                                     IdentifierInfo *FnName) {
7134
7135   // Don't crash if the user has the wrong number of arguments
7136   unsigned NumArgs = Call->getNumArgs();
7137   if ((NumArgs != 3) && (NumArgs != 4))
7138     return;
7139
7140   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7141   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7142   const Expr *CompareWithSrc = nullptr;
7143
7144   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7145                                      Call->getLocStart(), Call->getRParenLoc()))
7146     return;
7147   
7148   // Look for 'strlcpy(dst, x, sizeof(x))'
7149   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7150     CompareWithSrc = Ex;
7151   else {
7152     // Look for 'strlcpy(dst, x, strlen(x))'
7153     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7154       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7155           SizeCall->getNumArgs() == 1)
7156         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7157     }
7158   }
7159
7160   if (!CompareWithSrc)
7161     return;
7162
7163   // Determine if the argument to sizeof/strlen is equal to the source
7164   // argument.  In principle there's all kinds of things you could do
7165   // here, for instance creating an == expression and evaluating it with
7166   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7167   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7168   if (!SrcArgDRE)
7169     return;
7170   
7171   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7172   if (!CompareWithSrcDRE || 
7173       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7174     return;
7175   
7176   const Expr *OriginalSizeArg = Call->getArg(2);
7177   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7178     << OriginalSizeArg->getSourceRange() << FnName;
7179   
7180   // Output a FIXIT hint if the destination is an array (rather than a
7181   // pointer to an array).  This could be enhanced to handle some
7182   // pointers if we know the actual size, like if DstArg is 'array+2'
7183   // we could say 'sizeof(array)-2'.
7184   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7185   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7186     return;
7187
7188   SmallString<128> sizeString;
7189   llvm::raw_svector_ostream OS(sizeString);
7190   OS << "sizeof(";
7191   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7192   OS << ")";
7193   
7194   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7195     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7196                                     OS.str());
7197 }
7198
7199 /// Check if two expressions refer to the same declaration.
7200 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7201   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7202     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7203       return D1->getDecl() == D2->getDecl();
7204   return false;
7205 }
7206
7207 static const Expr *getStrlenExprArg(const Expr *E) {
7208   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7209     const FunctionDecl *FD = CE->getDirectCallee();
7210     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7211       return nullptr;
7212     return CE->getArg(0)->IgnoreParenCasts();
7213   }
7214   return nullptr;
7215 }
7216
7217 // Warn on anti-patterns as the 'size' argument to strncat.
7218 // The correct size argument should look like following:
7219 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7220 void Sema::CheckStrncatArguments(const CallExpr *CE,
7221                                  IdentifierInfo *FnName) {
7222   // Don't crash if the user has the wrong number of arguments.
7223   if (CE->getNumArgs() < 3)
7224     return;
7225   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7226   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7227   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7228
7229   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7230                                      CE->getRParenLoc()))
7231     return;
7232
7233   // Identify common expressions, which are wrongly used as the size argument
7234   // to strncat and may lead to buffer overflows.
7235   unsigned PatternType = 0;
7236   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7237     // - sizeof(dst)
7238     if (referToTheSameDecl(SizeOfArg, DstArg))
7239       PatternType = 1;
7240     // - sizeof(src)
7241     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7242       PatternType = 2;
7243   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7244     if (BE->getOpcode() == BO_Sub) {
7245       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7246       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7247       // - sizeof(dst) - strlen(dst)
7248       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7249           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7250         PatternType = 1;
7251       // - sizeof(src) - (anything)
7252       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7253         PatternType = 2;
7254     }
7255   }
7256
7257   if (PatternType == 0)
7258     return;
7259
7260   // Generate the diagnostic.
7261   SourceLocation SL = LenArg->getLocStart();
7262   SourceRange SR = LenArg->getSourceRange();
7263   SourceManager &SM = getSourceManager();
7264
7265   // If the function is defined as a builtin macro, do not show macro expansion.
7266   if (SM.isMacroArgExpansion(SL)) {
7267     SL = SM.getSpellingLoc(SL);
7268     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7269                      SM.getSpellingLoc(SR.getEnd()));
7270   }
7271
7272   // Check if the destination is an array (rather than a pointer to an array).
7273   QualType DstTy = DstArg->getType();
7274   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7275                                                                     Context);
7276   if (!isKnownSizeArray) {
7277     if (PatternType == 1)
7278       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7279     else
7280       Diag(SL, diag::warn_strncat_src_size) << SR;
7281     return;
7282   }
7283
7284   if (PatternType == 1)
7285     Diag(SL, diag::warn_strncat_large_size) << SR;
7286   else
7287     Diag(SL, diag::warn_strncat_src_size) << SR;
7288
7289   SmallString<128> sizeString;
7290   llvm::raw_svector_ostream OS(sizeString);
7291   OS << "sizeof(";
7292   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7293   OS << ") - ";
7294   OS << "strlen(";
7295   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7296   OS << ") - 1";
7297
7298   Diag(SL, diag::note_strncat_wrong_size)
7299     << FixItHint::CreateReplacement(SR, OS.str());
7300 }
7301
7302 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7303
7304 static const Expr *EvalVal(const Expr *E,
7305                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7306                            const Decl *ParentDecl);
7307 static const Expr *EvalAddr(const Expr *E,
7308                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7309                             const Decl *ParentDecl);
7310
7311 /// CheckReturnStackAddr - Check if a return statement returns the address
7312 ///   of a stack variable.
7313 static void
7314 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7315                      SourceLocation ReturnLoc) {
7316
7317   const Expr *stackE = nullptr;
7318   SmallVector<const DeclRefExpr *, 8> refVars;
7319
7320   // Perform checking for returned stack addresses, local blocks,
7321   // label addresses or references to temporaries.
7322   if (lhsType->isPointerType() ||
7323       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7324     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7325   } else if (lhsType->isReferenceType()) {
7326     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7327   }
7328
7329   if (!stackE)
7330     return; // Nothing suspicious was found.
7331
7332   // Parameters are initalized in the calling scope, so taking the address
7333   // of a parameter reference doesn't need a warning.
7334   for (auto *DRE : refVars)
7335     if (isa<ParmVarDecl>(DRE->getDecl()))
7336       return;
7337
7338   SourceLocation diagLoc;
7339   SourceRange diagRange;
7340   if (refVars.empty()) {
7341     diagLoc = stackE->getLocStart();
7342     diagRange = stackE->getSourceRange();
7343   } else {
7344     // We followed through a reference variable. 'stackE' contains the
7345     // problematic expression but we will warn at the return statement pointing
7346     // at the reference variable. We will later display the "trail" of
7347     // reference variables using notes.
7348     diagLoc = refVars[0]->getLocStart();
7349     diagRange = refVars[0]->getSourceRange();
7350   }
7351
7352   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7353     // address of local var
7354     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7355      << DR->getDecl()->getDeclName() << diagRange;
7356   } else if (isa<BlockExpr>(stackE)) { // local block.
7357     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7358   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7359     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7360   } else { // local temporary.
7361     // If there is an LValue->RValue conversion, then the value of the
7362     // reference type is used, not the reference.
7363     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7364       if (ICE->getCastKind() == CK_LValueToRValue) {
7365         return;
7366       }
7367     }
7368     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7369      << lhsType->isReferenceType() << diagRange;
7370   }
7371
7372   // Display the "trail" of reference variables that we followed until we
7373   // found the problematic expression using notes.
7374   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7375     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7376     // If this var binds to another reference var, show the range of the next
7377     // var, otherwise the var binds to the problematic expression, in which case
7378     // show the range of the expression.
7379     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7380                                     : stackE->getSourceRange();
7381     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7382         << VD->getDeclName() << range;
7383   }
7384 }
7385
7386 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7387 ///  check if the expression in a return statement evaluates to an address
7388 ///  to a location on the stack, a local block, an address of a label, or a
7389 ///  reference to local temporary. The recursion is used to traverse the
7390 ///  AST of the return expression, with recursion backtracking when we
7391 ///  encounter a subexpression that (1) clearly does not lead to one of the
7392 ///  above problematic expressions (2) is something we cannot determine leads to
7393 ///  a problematic expression based on such local checking.
7394 ///
7395 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7396 ///  the expression that they point to. Such variables are added to the
7397 ///  'refVars' vector so that we know what the reference variable "trail" was.
7398 ///
7399 ///  EvalAddr processes expressions that are pointers that are used as
7400 ///  references (and not L-values).  EvalVal handles all other values.
7401 ///  At the base case of the recursion is a check for the above problematic
7402 ///  expressions.
7403 ///
7404 ///  This implementation handles:
7405 ///
7406 ///   * pointer-to-pointer casts
7407 ///   * implicit conversions from array references to pointers
7408 ///   * taking the address of fields
7409 ///   * arbitrary interplay between "&" and "*" operators
7410 ///   * pointer arithmetic from an address of a stack variable
7411 ///   * taking the address of an array element where the array is on the stack
7412 static const Expr *EvalAddr(const Expr *E,
7413                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7414                             const Decl *ParentDecl) {
7415   if (E->isTypeDependent())
7416     return nullptr;
7417
7418   // We should only be called for evaluating pointer expressions.
7419   assert((E->getType()->isAnyPointerType() ||
7420           E->getType()->isBlockPointerType() ||
7421           E->getType()->isObjCQualifiedIdType()) &&
7422          "EvalAddr only works on pointers");
7423
7424   E = E->IgnoreParens();
7425
7426   // Our "symbolic interpreter" is just a dispatch off the currently
7427   // viewed AST node.  We then recursively traverse the AST by calling
7428   // EvalAddr and EvalVal appropriately.
7429   switch (E->getStmtClass()) {
7430   case Stmt::DeclRefExprClass: {
7431     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7432
7433     // If we leave the immediate function, the lifetime isn't about to end.
7434     if (DR->refersToEnclosingVariableOrCapture())
7435       return nullptr;
7436
7437     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7438       // If this is a reference variable, follow through to the expression that
7439       // it points to.
7440       if (V->hasLocalStorage() &&
7441           V->getType()->isReferenceType() && V->hasInit()) {
7442         // Add the reference variable to the "trail".
7443         refVars.push_back(DR);
7444         return EvalAddr(V->getInit(), refVars, ParentDecl);
7445       }
7446
7447     return nullptr;
7448   }
7449
7450   case Stmt::UnaryOperatorClass: {
7451     // The only unary operator that make sense to handle here
7452     // is AddrOf.  All others don't make sense as pointers.
7453     const UnaryOperator *U = cast<UnaryOperator>(E);
7454
7455     if (U->getOpcode() == UO_AddrOf)
7456       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7457     return nullptr;
7458   }
7459
7460   case Stmt::BinaryOperatorClass: {
7461     // Handle pointer arithmetic.  All other binary operators are not valid
7462     // in this context.
7463     const BinaryOperator *B = cast<BinaryOperator>(E);
7464     BinaryOperatorKind op = B->getOpcode();
7465
7466     if (op != BO_Add && op != BO_Sub)
7467       return nullptr;
7468
7469     const Expr *Base = B->getLHS();
7470
7471     // Determine which argument is the real pointer base.  It could be
7472     // the RHS argument instead of the LHS.
7473     if (!Base->getType()->isPointerType())
7474       Base = B->getRHS();
7475
7476     assert(Base->getType()->isPointerType());
7477     return EvalAddr(Base, refVars, ParentDecl);
7478   }
7479
7480   // For conditional operators we need to see if either the LHS or RHS are
7481   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7482   case Stmt::ConditionalOperatorClass: {
7483     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7484
7485     // Handle the GNU extension for missing LHS.
7486     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7487     if (const Expr *LHSExpr = C->getLHS()) {
7488       // In C++, we can have a throw-expression, which has 'void' type.
7489       if (!LHSExpr->getType()->isVoidType())
7490         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7491           return LHS;
7492     }
7493
7494     // In C++, we can have a throw-expression, which has 'void' type.
7495     if (C->getRHS()->getType()->isVoidType())
7496       return nullptr;
7497
7498     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7499   }
7500
7501   case Stmt::BlockExprClass:
7502     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7503       return E; // local block.
7504     return nullptr;
7505
7506   case Stmt::AddrLabelExprClass:
7507     return E; // address of label.
7508
7509   case Stmt::ExprWithCleanupsClass:
7510     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7511                     ParentDecl);
7512
7513   // For casts, we need to handle conversions from arrays to
7514   // pointer values, and pointer-to-pointer conversions.
7515   case Stmt::ImplicitCastExprClass:
7516   case Stmt::CStyleCastExprClass:
7517   case Stmt::CXXFunctionalCastExprClass:
7518   case Stmt::ObjCBridgedCastExprClass:
7519   case Stmt::CXXStaticCastExprClass:
7520   case Stmt::CXXDynamicCastExprClass:
7521   case Stmt::CXXConstCastExprClass:
7522   case Stmt::CXXReinterpretCastExprClass: {
7523     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7524     switch (cast<CastExpr>(E)->getCastKind()) {
7525     case CK_LValueToRValue:
7526     case CK_NoOp:
7527     case CK_BaseToDerived:
7528     case CK_DerivedToBase:
7529     case CK_UncheckedDerivedToBase:
7530     case CK_Dynamic:
7531     case CK_CPointerToObjCPointerCast:
7532     case CK_BlockPointerToObjCPointerCast:
7533     case CK_AnyPointerToBlockPointerCast:
7534       return EvalAddr(SubExpr, refVars, ParentDecl);
7535
7536     case CK_ArrayToPointerDecay:
7537       return EvalVal(SubExpr, refVars, ParentDecl);
7538
7539     case CK_BitCast:
7540       if (SubExpr->getType()->isAnyPointerType() ||
7541           SubExpr->getType()->isBlockPointerType() ||
7542           SubExpr->getType()->isObjCQualifiedIdType())
7543         return EvalAddr(SubExpr, refVars, ParentDecl);
7544       else
7545         return nullptr;
7546
7547     default:
7548       return nullptr;
7549     }
7550   }
7551
7552   case Stmt::MaterializeTemporaryExprClass:
7553     if (const Expr *Result =
7554             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7555                      refVars, ParentDecl))
7556       return Result;
7557     return E;
7558
7559   // Everything else: we simply don't reason about them.
7560   default:
7561     return nullptr;
7562   }
7563 }
7564
7565 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7566 ///   See the comments for EvalAddr for more details.
7567 static const Expr *EvalVal(const Expr *E,
7568                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7569                            const Decl *ParentDecl) {
7570   do {
7571     // We should only be called for evaluating non-pointer expressions, or
7572     // expressions with a pointer type that are not used as references but
7573     // instead
7574     // are l-values (e.g., DeclRefExpr with a pointer type).
7575
7576     // Our "symbolic interpreter" is just a dispatch off the currently
7577     // viewed AST node.  We then recursively traverse the AST by calling
7578     // EvalAddr and EvalVal appropriately.
7579
7580     E = E->IgnoreParens();
7581     switch (E->getStmtClass()) {
7582     case Stmt::ImplicitCastExprClass: {
7583       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7584       if (IE->getValueKind() == VK_LValue) {
7585         E = IE->getSubExpr();
7586         continue;
7587       }
7588       return nullptr;
7589     }
7590
7591     case Stmt::ExprWithCleanupsClass:
7592       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7593                      ParentDecl);
7594
7595     case Stmt::DeclRefExprClass: {
7596       // When we hit a DeclRefExpr we are looking at code that refers to a
7597       // variable's name. If it's not a reference variable we check if it has
7598       // local storage within the function, and if so, return the expression.
7599       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7600
7601       // If we leave the immediate function, the lifetime isn't about to end.
7602       if (DR->refersToEnclosingVariableOrCapture())
7603         return nullptr;
7604
7605       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7606         // Check if it refers to itself, e.g. "int& i = i;".
7607         if (V == ParentDecl)
7608           return DR;
7609
7610         if (V->hasLocalStorage()) {
7611           if (!V->getType()->isReferenceType())
7612             return DR;
7613
7614           // Reference variable, follow through to the expression that
7615           // it points to.
7616           if (V->hasInit()) {
7617             // Add the reference variable to the "trail".
7618             refVars.push_back(DR);
7619             return EvalVal(V->getInit(), refVars, V);
7620           }
7621         }
7622       }
7623
7624       return nullptr;
7625     }
7626
7627     case Stmt::UnaryOperatorClass: {
7628       // The only unary operator that make sense to handle here
7629       // is Deref.  All others don't resolve to a "name."  This includes
7630       // handling all sorts of rvalues passed to a unary operator.
7631       const UnaryOperator *U = cast<UnaryOperator>(E);
7632
7633       if (U->getOpcode() == UO_Deref)
7634         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7635
7636       return nullptr;
7637     }
7638
7639     case Stmt::ArraySubscriptExprClass: {
7640       // Array subscripts are potential references to data on the stack.  We
7641       // retrieve the DeclRefExpr* for the array variable if it indeed
7642       // has local storage.
7643       const auto *ASE = cast<ArraySubscriptExpr>(E);
7644       if (ASE->isTypeDependent())
7645         return nullptr;
7646       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7647     }
7648
7649     case Stmt::OMPArraySectionExprClass: {
7650       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7651                       ParentDecl);
7652     }
7653
7654     case Stmt::ConditionalOperatorClass: {
7655       // For conditional operators we need to see if either the LHS or RHS are
7656       // non-NULL Expr's.  If one is non-NULL, we return it.
7657       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7658
7659       // Handle the GNU extension for missing LHS.
7660       if (const Expr *LHSExpr = C->getLHS()) {
7661         // In C++, we can have a throw-expression, which has 'void' type.
7662         if (!LHSExpr->getType()->isVoidType())
7663           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7664             return LHS;
7665       }
7666
7667       // In C++, we can have a throw-expression, which has 'void' type.
7668       if (C->getRHS()->getType()->isVoidType())
7669         return nullptr;
7670
7671       return EvalVal(C->getRHS(), refVars, ParentDecl);
7672     }
7673
7674     // Accesses to members are potential references to data on the stack.
7675     case Stmt::MemberExprClass: {
7676       const MemberExpr *M = cast<MemberExpr>(E);
7677
7678       // Check for indirect access.  We only want direct field accesses.
7679       if (M->isArrow())
7680         return nullptr;
7681
7682       // Check whether the member type is itself a reference, in which case
7683       // we're not going to refer to the member, but to what the member refers
7684       // to.
7685       if (M->getMemberDecl()->getType()->isReferenceType())
7686         return nullptr;
7687
7688       return EvalVal(M->getBase(), refVars, ParentDecl);
7689     }
7690
7691     case Stmt::MaterializeTemporaryExprClass:
7692       if (const Expr *Result =
7693               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7694                       refVars, ParentDecl))
7695         return Result;
7696       return E;
7697
7698     default:
7699       // Check that we don't return or take the address of a reference to a
7700       // temporary. This is only useful in C++.
7701       if (!E->isTypeDependent() && E->isRValue())
7702         return E;
7703
7704       // Everything else: we simply don't reason about them.
7705       return nullptr;
7706     }
7707   } while (true);
7708 }
7709
7710 void
7711 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7712                          SourceLocation ReturnLoc,
7713                          bool isObjCMethod,
7714                          const AttrVec *Attrs,
7715                          const FunctionDecl *FD) {
7716   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7717
7718   // Check if the return value is null but should not be.
7719   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7720        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7721       CheckNonNullExpr(*this, RetValExp))
7722     Diag(ReturnLoc, diag::warn_null_ret)
7723       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7724
7725   // C++11 [basic.stc.dynamic.allocation]p4:
7726   //   If an allocation function declared with a non-throwing
7727   //   exception-specification fails to allocate storage, it shall return
7728   //   a null pointer. Any other allocation function that fails to allocate
7729   //   storage shall indicate failure only by throwing an exception [...]
7730   if (FD) {
7731     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7732     if (Op == OO_New || Op == OO_Array_New) {
7733       const FunctionProtoType *Proto
7734         = FD->getType()->castAs<FunctionProtoType>();
7735       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7736           CheckNonNullExpr(*this, RetValExp))
7737         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7738           << FD << getLangOpts().CPlusPlus11;
7739     }
7740   }
7741 }
7742
7743 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7744
7745 /// Check for comparisons of floating point operands using != and ==.
7746 /// Issue a warning if these are no self-comparisons, as they are not likely
7747 /// to do what the programmer intended.
7748 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7749   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7750   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7751
7752   // Special case: check for x == x (which is OK).
7753   // Do not emit warnings for such cases.
7754   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7755     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7756       if (DRL->getDecl() == DRR->getDecl())
7757         return;
7758
7759   // Special case: check for comparisons against literals that can be exactly
7760   //  represented by APFloat.  In such cases, do not emit a warning.  This
7761   //  is a heuristic: often comparison against such literals are used to
7762   //  detect if a value in a variable has not changed.  This clearly can
7763   //  lead to false negatives.
7764   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7765     if (FLL->isExact())
7766       return;
7767   } else
7768     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7769       if (FLR->isExact())
7770         return;
7771
7772   // Check for comparisons with builtin types.
7773   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7774     if (CL->getBuiltinCallee())
7775       return;
7776
7777   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7778     if (CR->getBuiltinCallee())
7779       return;
7780
7781   // Emit the diagnostic.
7782   Diag(Loc, diag::warn_floatingpoint_eq)
7783     << LHS->getSourceRange() << RHS->getSourceRange();
7784 }
7785
7786 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7787 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7788
7789 namespace {
7790
7791 /// Structure recording the 'active' range of an integer-valued
7792 /// expression.
7793 struct IntRange {
7794   /// The number of bits active in the int.
7795   unsigned Width;
7796
7797   /// True if the int is known not to have negative values.
7798   bool NonNegative;
7799
7800   IntRange(unsigned Width, bool NonNegative)
7801     : Width(Width), NonNegative(NonNegative)
7802   {}
7803
7804   /// Returns the range of the bool type.
7805   static IntRange forBoolType() {
7806     return IntRange(1, true);
7807   }
7808
7809   /// Returns the range of an opaque value of the given integral type.
7810   static IntRange forValueOfType(ASTContext &C, QualType T) {
7811     return forValueOfCanonicalType(C,
7812                           T->getCanonicalTypeInternal().getTypePtr());
7813   }
7814
7815   /// Returns the range of an opaque value of a canonical integral type.
7816   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7817     assert(T->isCanonicalUnqualified());
7818
7819     if (const VectorType *VT = dyn_cast<VectorType>(T))
7820       T = VT->getElementType().getTypePtr();
7821     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7822       T = CT->getElementType().getTypePtr();
7823     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7824       T = AT->getValueType().getTypePtr();
7825
7826     // For enum types, use the known bit width of the enumerators.
7827     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7828       EnumDecl *Enum = ET->getDecl();
7829       if (!Enum->isCompleteDefinition())
7830         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7831
7832       unsigned NumPositive = Enum->getNumPositiveBits();
7833       unsigned NumNegative = Enum->getNumNegativeBits();
7834
7835       if (NumNegative == 0)
7836         return IntRange(NumPositive, true/*NonNegative*/);
7837       else
7838         return IntRange(std::max(NumPositive + 1, NumNegative),
7839                         false/*NonNegative*/);
7840     }
7841
7842     const BuiltinType *BT = cast<BuiltinType>(T);
7843     assert(BT->isInteger());
7844
7845     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7846   }
7847
7848   /// Returns the "target" range of a canonical integral type, i.e.
7849   /// the range of values expressible in the type.
7850   ///
7851   /// This matches forValueOfCanonicalType except that enums have the
7852   /// full range of their type, not the range of their enumerators.
7853   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7854     assert(T->isCanonicalUnqualified());
7855
7856     if (const VectorType *VT = dyn_cast<VectorType>(T))
7857       T = VT->getElementType().getTypePtr();
7858     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7859       T = CT->getElementType().getTypePtr();
7860     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7861       T = AT->getValueType().getTypePtr();
7862     if (const EnumType *ET = dyn_cast<EnumType>(T))
7863       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7864
7865     const BuiltinType *BT = cast<BuiltinType>(T);
7866     assert(BT->isInteger());
7867
7868     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7869   }
7870
7871   /// Returns the supremum of two ranges: i.e. their conservative merge.
7872   static IntRange join(IntRange L, IntRange R) {
7873     return IntRange(std::max(L.Width, R.Width),
7874                     L.NonNegative && R.NonNegative);
7875   }
7876
7877   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7878   static IntRange meet(IntRange L, IntRange R) {
7879     return IntRange(std::min(L.Width, R.Width),
7880                     L.NonNegative || R.NonNegative);
7881   }
7882 };
7883
7884 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7885   if (value.isSigned() && value.isNegative())
7886     return IntRange(value.getMinSignedBits(), false);
7887
7888   if (value.getBitWidth() > MaxWidth)
7889     value = value.trunc(MaxWidth);
7890
7891   // isNonNegative() just checks the sign bit without considering
7892   // signedness.
7893   return IntRange(value.getActiveBits(), true);
7894 }
7895
7896 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7897                        unsigned MaxWidth) {
7898   if (result.isInt())
7899     return GetValueRange(C, result.getInt(), MaxWidth);
7900
7901   if (result.isVector()) {
7902     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7903     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7904       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7905       R = IntRange::join(R, El);
7906     }
7907     return R;
7908   }
7909
7910   if (result.isComplexInt()) {
7911     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7912     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7913     return IntRange::join(R, I);
7914   }
7915
7916   // This can happen with lossless casts to intptr_t of "based" lvalues.
7917   // Assume it might use arbitrary bits.
7918   // FIXME: The only reason we need to pass the type in here is to get
7919   // the sign right on this one case.  It would be nice if APValue
7920   // preserved this.
7921   assert(result.isLValue() || result.isAddrLabelDiff());
7922   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7923 }
7924
7925 QualType GetExprType(const Expr *E) {
7926   QualType Ty = E->getType();
7927   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7928     Ty = AtomicRHS->getValueType();
7929   return Ty;
7930 }
7931
7932 /// Pseudo-evaluate the given integer expression, estimating the
7933 /// range of values it might take.
7934 ///
7935 /// \param MaxWidth - the width to which the value will be truncated
7936 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7937   E = E->IgnoreParens();
7938
7939   // Try a full evaluation first.
7940   Expr::EvalResult result;
7941   if (E->EvaluateAsRValue(result, C))
7942     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7943
7944   // I think we only want to look through implicit casts here; if the
7945   // user has an explicit widening cast, we should treat the value as
7946   // being of the new, wider type.
7947   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7948     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7949       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7950
7951     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7952
7953     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7954                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7955
7956     // Assume that non-integer casts can span the full range of the type.
7957     if (!isIntegerCast)
7958       return OutputTypeRange;
7959
7960     IntRange SubRange
7961       = GetExprRange(C, CE->getSubExpr(),
7962                      std::min(MaxWidth, OutputTypeRange.Width));
7963
7964     // Bail out if the subexpr's range is as wide as the cast type.
7965     if (SubRange.Width >= OutputTypeRange.Width)
7966       return OutputTypeRange;
7967
7968     // Otherwise, we take the smaller width, and we're non-negative if
7969     // either the output type or the subexpr is.
7970     return IntRange(SubRange.Width,
7971                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7972   }
7973
7974   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7975     // If we can fold the condition, just take that operand.
7976     bool CondResult;
7977     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7978       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7979                                         : CO->getFalseExpr(),
7980                           MaxWidth);
7981
7982     // Otherwise, conservatively merge.
7983     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7984     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7985     return IntRange::join(L, R);
7986   }
7987
7988   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7989     switch (BO->getOpcode()) {
7990
7991     // Boolean-valued operations are single-bit and positive.
7992     case BO_LAnd:
7993     case BO_LOr:
7994     case BO_LT:
7995     case BO_GT:
7996     case BO_LE:
7997     case BO_GE:
7998     case BO_EQ:
7999     case BO_NE:
8000       return IntRange::forBoolType();
8001
8002     // The type of the assignments is the type of the LHS, so the RHS
8003     // is not necessarily the same type.
8004     case BO_MulAssign:
8005     case BO_DivAssign:
8006     case BO_RemAssign:
8007     case BO_AddAssign:
8008     case BO_SubAssign:
8009     case BO_XorAssign:
8010     case BO_OrAssign:
8011       // TODO: bitfields?
8012       return IntRange::forValueOfType(C, GetExprType(E));
8013
8014     // Simple assignments just pass through the RHS, which will have
8015     // been coerced to the LHS type.
8016     case BO_Assign:
8017       // TODO: bitfields?
8018       return GetExprRange(C, BO->getRHS(), MaxWidth);
8019
8020     // Operations with opaque sources are black-listed.
8021     case BO_PtrMemD:
8022     case BO_PtrMemI:
8023       return IntRange::forValueOfType(C, GetExprType(E));
8024
8025     // Bitwise-and uses the *infinum* of the two source ranges.
8026     case BO_And:
8027     case BO_AndAssign:
8028       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8029                             GetExprRange(C, BO->getRHS(), MaxWidth));
8030
8031     // Left shift gets black-listed based on a judgement call.
8032     case BO_Shl:
8033       // ...except that we want to treat '1 << (blah)' as logically
8034       // positive.  It's an important idiom.
8035       if (IntegerLiteral *I
8036             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8037         if (I->getValue() == 1) {
8038           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8039           return IntRange(R.Width, /*NonNegative*/ true);
8040         }
8041       }
8042       // fallthrough
8043
8044     case BO_ShlAssign:
8045       return IntRange::forValueOfType(C, GetExprType(E));
8046
8047     // Right shift by a constant can narrow its left argument.
8048     case BO_Shr:
8049     case BO_ShrAssign: {
8050       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8051
8052       // If the shift amount is a positive constant, drop the width by
8053       // that much.
8054       llvm::APSInt shift;
8055       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8056           shift.isNonNegative()) {
8057         unsigned zext = shift.getZExtValue();
8058         if (zext >= L.Width)
8059           L.Width = (L.NonNegative ? 0 : 1);
8060         else
8061           L.Width -= zext;
8062       }
8063
8064       return L;
8065     }
8066
8067     // Comma acts as its right operand.
8068     case BO_Comma:
8069       return GetExprRange(C, BO->getRHS(), MaxWidth);
8070
8071     // Black-list pointer subtractions.
8072     case BO_Sub:
8073       if (BO->getLHS()->getType()->isPointerType())
8074         return IntRange::forValueOfType(C, GetExprType(E));
8075       break;
8076
8077     // The width of a division result is mostly determined by the size
8078     // of the LHS.
8079     case BO_Div: {
8080       // Don't 'pre-truncate' the operands.
8081       unsigned opWidth = C.getIntWidth(GetExprType(E));
8082       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8083
8084       // If the divisor is constant, use that.
8085       llvm::APSInt divisor;
8086       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8087         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8088         if (log2 >= L.Width)
8089           L.Width = (L.NonNegative ? 0 : 1);
8090         else
8091           L.Width = std::min(L.Width - log2, MaxWidth);
8092         return L;
8093       }
8094
8095       // Otherwise, just use the LHS's width.
8096       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8097       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8098     }
8099
8100     // The result of a remainder can't be larger than the result of
8101     // either side.
8102     case BO_Rem: {
8103       // Don't 'pre-truncate' the operands.
8104       unsigned opWidth = C.getIntWidth(GetExprType(E));
8105       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8106       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8107
8108       IntRange meet = IntRange::meet(L, R);
8109       meet.Width = std::min(meet.Width, MaxWidth);
8110       return meet;
8111     }
8112
8113     // The default behavior is okay for these.
8114     case BO_Mul:
8115     case BO_Add:
8116     case BO_Xor:
8117     case BO_Or:
8118       break;
8119     }
8120
8121     // The default case is to treat the operation as if it were closed
8122     // on the narrowest type that encompasses both operands.
8123     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8124     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8125     return IntRange::join(L, R);
8126   }
8127
8128   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8129     switch (UO->getOpcode()) {
8130     // Boolean-valued operations are white-listed.
8131     case UO_LNot:
8132       return IntRange::forBoolType();
8133
8134     // Operations with opaque sources are black-listed.
8135     case UO_Deref:
8136     case UO_AddrOf: // should be impossible
8137       return IntRange::forValueOfType(C, GetExprType(E));
8138
8139     default:
8140       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8141     }
8142   }
8143
8144   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8145     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8146
8147   if (const auto *BitField = E->getSourceBitField())
8148     return IntRange(BitField->getBitWidthValue(C),
8149                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8150
8151   return IntRange::forValueOfType(C, GetExprType(E));
8152 }
8153
8154 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8155   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8156 }
8157
8158 /// Checks whether the given value, which currently has the given
8159 /// source semantics, has the same value when coerced through the
8160 /// target semantics.
8161 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8162                           const llvm::fltSemantics &Src,
8163                           const llvm::fltSemantics &Tgt) {
8164   llvm::APFloat truncated = value;
8165
8166   bool ignored;
8167   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8168   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8169
8170   return truncated.bitwiseIsEqual(value);
8171 }
8172
8173 /// Checks whether the given value, which currently has the given
8174 /// source semantics, has the same value when coerced through the
8175 /// target semantics.
8176 ///
8177 /// The value might be a vector of floats (or a complex number).
8178 bool IsSameFloatAfterCast(const APValue &value,
8179                           const llvm::fltSemantics &Src,
8180                           const llvm::fltSemantics &Tgt) {
8181   if (value.isFloat())
8182     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8183
8184   if (value.isVector()) {
8185     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8186       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8187         return false;
8188     return true;
8189   }
8190
8191   assert(value.isComplexFloat());
8192   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8193           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8194 }
8195
8196 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8197
8198 bool IsZero(Sema &S, Expr *E) {
8199   // Suppress cases where we are comparing against an enum constant.
8200   if (const DeclRefExpr *DR =
8201       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8202     if (isa<EnumConstantDecl>(DR->getDecl()))
8203       return false;
8204
8205   // Suppress cases where the '0' value is expanded from a macro.
8206   if (E->getLocStart().isMacroID())
8207     return false;
8208
8209   llvm::APSInt Value;
8210   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8211 }
8212
8213 bool HasEnumType(Expr *E) {
8214   // Strip off implicit integral promotions.
8215   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8216     if (ICE->getCastKind() != CK_IntegralCast &&
8217         ICE->getCastKind() != CK_NoOp)
8218       break;
8219     E = ICE->getSubExpr();
8220   }
8221
8222   return E->getType()->isEnumeralType();
8223 }
8224
8225 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8226   // Disable warning in template instantiations.
8227   if (!S.ActiveTemplateInstantiations.empty())
8228     return;
8229
8230   BinaryOperatorKind op = E->getOpcode();
8231   if (E->isValueDependent())
8232     return;
8233
8234   if (op == BO_LT && IsZero(S, E->getRHS())) {
8235     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8236       << "< 0" << "false" << HasEnumType(E->getLHS())
8237       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8238   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8239     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8240       << ">= 0" << "true" << HasEnumType(E->getLHS())
8241       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8242   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8243     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8244       << "0 >" << "false" << HasEnumType(E->getRHS())
8245       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8246   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8247     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8248       << "0 <=" << "true" << HasEnumType(E->getRHS())
8249       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8250   }
8251 }
8252
8253 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8254                                   Expr *Other, const llvm::APSInt &Value,
8255                                   bool RhsConstant) {
8256   // Disable warning in template instantiations.
8257   if (!S.ActiveTemplateInstantiations.empty())
8258     return;
8259
8260   // TODO: Investigate using GetExprRange() to get tighter bounds
8261   // on the bit ranges.
8262   QualType OtherT = Other->getType();
8263   if (const auto *AT = OtherT->getAs<AtomicType>())
8264     OtherT = AT->getValueType();
8265   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8266   unsigned OtherWidth = OtherRange.Width;
8267
8268   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8269
8270   // 0 values are handled later by CheckTrivialUnsignedComparison().
8271   if ((Value == 0) && (!OtherIsBooleanType))
8272     return;
8273
8274   BinaryOperatorKind op = E->getOpcode();
8275   bool IsTrue = true;
8276
8277   // Used for diagnostic printout.
8278   enum {
8279     LiteralConstant = 0,
8280     CXXBoolLiteralTrue,
8281     CXXBoolLiteralFalse
8282   } LiteralOrBoolConstant = LiteralConstant;
8283
8284   if (!OtherIsBooleanType) {
8285     QualType ConstantT = Constant->getType();
8286     QualType CommonT = E->getLHS()->getType();
8287
8288     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8289       return;
8290     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8291            "comparison with non-integer type");
8292
8293     bool ConstantSigned = ConstantT->isSignedIntegerType();
8294     bool CommonSigned = CommonT->isSignedIntegerType();
8295
8296     bool EqualityOnly = false;
8297
8298     if (CommonSigned) {
8299       // The common type is signed, therefore no signed to unsigned conversion.
8300       if (!OtherRange.NonNegative) {
8301         // Check that the constant is representable in type OtherT.
8302         if (ConstantSigned) {
8303           if (OtherWidth >= Value.getMinSignedBits())
8304             return;
8305         } else { // !ConstantSigned
8306           if (OtherWidth >= Value.getActiveBits() + 1)
8307             return;
8308         }
8309       } else { // !OtherSigned
8310                // Check that the constant is representable in type OtherT.
8311         // Negative values are out of range.
8312         if (ConstantSigned) {
8313           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8314             return;
8315         } else { // !ConstantSigned
8316           if (OtherWidth >= Value.getActiveBits())
8317             return;
8318         }
8319       }
8320     } else { // !CommonSigned
8321       if (OtherRange.NonNegative) {
8322         if (OtherWidth >= Value.getActiveBits())
8323           return;
8324       } else { // OtherSigned
8325         assert(!ConstantSigned &&
8326                "Two signed types converted to unsigned types.");
8327         // Check to see if the constant is representable in OtherT.
8328         if (OtherWidth > Value.getActiveBits())
8329           return;
8330         // Check to see if the constant is equivalent to a negative value
8331         // cast to CommonT.
8332         if (S.Context.getIntWidth(ConstantT) ==
8333                 S.Context.getIntWidth(CommonT) &&
8334             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8335           return;
8336         // The constant value rests between values that OtherT can represent
8337         // after conversion.  Relational comparison still works, but equality
8338         // comparisons will be tautological.
8339         EqualityOnly = true;
8340       }
8341     }
8342
8343     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8344
8345     if (op == BO_EQ || op == BO_NE) {
8346       IsTrue = op == BO_NE;
8347     } else if (EqualityOnly) {
8348       return;
8349     } else if (RhsConstant) {
8350       if (op == BO_GT || op == BO_GE)
8351         IsTrue = !PositiveConstant;
8352       else // op == BO_LT || op == BO_LE
8353         IsTrue = PositiveConstant;
8354     } else {
8355       if (op == BO_LT || op == BO_LE)
8356         IsTrue = !PositiveConstant;
8357       else // op == BO_GT || op == BO_GE
8358         IsTrue = PositiveConstant;
8359     }
8360   } else {
8361     // Other isKnownToHaveBooleanValue
8362     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8363     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8364     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8365
8366     static const struct LinkedConditions {
8367       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8368       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8369       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8370       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8371       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8372       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8373
8374     } TruthTable = {
8375         // Constant on LHS.              | Constant on RHS.              |
8376         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8377         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8378         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8379         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8380         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8381         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8382         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8383       };
8384
8385     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8386
8387     enum ConstantValue ConstVal = Zero;
8388     if (Value.isUnsigned() || Value.isNonNegative()) {
8389       if (Value == 0) {
8390         LiteralOrBoolConstant =
8391             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8392         ConstVal = Zero;
8393       } else if (Value == 1) {
8394         LiteralOrBoolConstant =
8395             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8396         ConstVal = One;
8397       } else {
8398         LiteralOrBoolConstant = LiteralConstant;
8399         ConstVal = GT_One;
8400       }
8401     } else {
8402       ConstVal = LT_Zero;
8403     }
8404
8405     CompareBoolWithConstantResult CmpRes;
8406
8407     switch (op) {
8408     case BO_LT:
8409       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8410       break;
8411     case BO_GT:
8412       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8413       break;
8414     case BO_LE:
8415       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8416       break;
8417     case BO_GE:
8418       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8419       break;
8420     case BO_EQ:
8421       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8422       break;
8423     case BO_NE:
8424       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8425       break;
8426     default:
8427       CmpRes = Unkwn;
8428       break;
8429     }
8430
8431     if (CmpRes == AFals) {
8432       IsTrue = false;
8433     } else if (CmpRes == ATrue) {
8434       IsTrue = true;
8435     } else {
8436       return;
8437     }
8438   }
8439
8440   // If this is a comparison to an enum constant, include that
8441   // constant in the diagnostic.
8442   const EnumConstantDecl *ED = nullptr;
8443   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8444     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8445
8446   SmallString<64> PrettySourceValue;
8447   llvm::raw_svector_ostream OS(PrettySourceValue);
8448   if (ED)
8449     OS << '\'' << *ED << "' (" << Value << ")";
8450   else
8451     OS << Value;
8452
8453   S.DiagRuntimeBehavior(
8454     E->getOperatorLoc(), E,
8455     S.PDiag(diag::warn_out_of_range_compare)
8456         << OS.str() << LiteralOrBoolConstant
8457         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8458         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8459 }
8460
8461 /// Analyze the operands of the given comparison.  Implements the
8462 /// fallback case from AnalyzeComparison.
8463 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8464   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8465   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8466 }
8467
8468 /// \brief Implements -Wsign-compare.
8469 ///
8470 /// \param E the binary operator to check for warnings
8471 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8472   // The type the comparison is being performed in.
8473   QualType T = E->getLHS()->getType();
8474
8475   // Only analyze comparison operators where both sides have been converted to
8476   // the same type.
8477   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8478     return AnalyzeImpConvsInComparison(S, E);
8479
8480   // Don't analyze value-dependent comparisons directly.
8481   if (E->isValueDependent())
8482     return AnalyzeImpConvsInComparison(S, E);
8483
8484   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8485   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8486   
8487   bool IsComparisonConstant = false;
8488   
8489   // Check whether an integer constant comparison results in a value
8490   // of 'true' or 'false'.
8491   if (T->isIntegralType(S.Context)) {
8492     llvm::APSInt RHSValue;
8493     bool IsRHSIntegralLiteral = 
8494       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8495     llvm::APSInt LHSValue;
8496     bool IsLHSIntegralLiteral = 
8497       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8498     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8499         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8500     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8501       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8502     else
8503       IsComparisonConstant = 
8504         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8505   } else if (!T->hasUnsignedIntegerRepresentation())
8506       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8507   
8508   // We don't do anything special if this isn't an unsigned integral
8509   // comparison:  we're only interested in integral comparisons, and
8510   // signed comparisons only happen in cases we don't care to warn about.
8511   //
8512   // We also don't care about value-dependent expressions or expressions
8513   // whose result is a constant.
8514   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8515     return AnalyzeImpConvsInComparison(S, E);
8516   
8517   // Check to see if one of the (unmodified) operands is of different
8518   // signedness.
8519   Expr *signedOperand, *unsignedOperand;
8520   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8521     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8522            "unsigned comparison between two signed integer expressions?");
8523     signedOperand = LHS;
8524     unsignedOperand = RHS;
8525   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8526     signedOperand = RHS;
8527     unsignedOperand = LHS;
8528   } else {
8529     CheckTrivialUnsignedComparison(S, E);
8530     return AnalyzeImpConvsInComparison(S, E);
8531   }
8532
8533   // Otherwise, calculate the effective range of the signed operand.
8534   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8535
8536   // Go ahead and analyze implicit conversions in the operands.  Note
8537   // that we skip the implicit conversions on both sides.
8538   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8539   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8540
8541   // If the signed range is non-negative, -Wsign-compare won't fire,
8542   // but we should still check for comparisons which are always true
8543   // or false.
8544   if (signedRange.NonNegative)
8545     return CheckTrivialUnsignedComparison(S, E);
8546
8547   // For (in)equality comparisons, if the unsigned operand is a
8548   // constant which cannot collide with a overflowed signed operand,
8549   // then reinterpreting the signed operand as unsigned will not
8550   // change the result of the comparison.
8551   if (E->isEqualityOp()) {
8552     unsigned comparisonWidth = S.Context.getIntWidth(T);
8553     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8554
8555     // We should never be unable to prove that the unsigned operand is
8556     // non-negative.
8557     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8558
8559     if (unsignedRange.Width < comparisonWidth)
8560       return;
8561   }
8562
8563   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8564     S.PDiag(diag::warn_mixed_sign_comparison)
8565       << LHS->getType() << RHS->getType()
8566       << LHS->getSourceRange() << RHS->getSourceRange());
8567 }
8568
8569 /// Analyzes an attempt to assign the given value to a bitfield.
8570 ///
8571 /// Returns true if there was something fishy about the attempt.
8572 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8573                                SourceLocation InitLoc) {
8574   assert(Bitfield->isBitField());
8575   if (Bitfield->isInvalidDecl())
8576     return false;
8577
8578   // White-list bool bitfields.
8579   QualType BitfieldType = Bitfield->getType();
8580   if (BitfieldType->isBooleanType())
8581      return false;
8582
8583   if (BitfieldType->isEnumeralType()) {
8584     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8585     // If the underlying enum type was not explicitly specified as an unsigned
8586     // type and the enum contain only positive values, MSVC++ will cause an
8587     // inconsistency by storing this as a signed type.
8588     if (S.getLangOpts().CPlusPlus11 &&
8589         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8590         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8591         BitfieldEnumDecl->getNumNegativeBits() == 0) {
8592       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8593         << BitfieldEnumDecl->getNameAsString();
8594     }
8595   }
8596
8597   if (Bitfield->getType()->isBooleanType())
8598     return false;
8599
8600   // Ignore value- or type-dependent expressions.
8601   if (Bitfield->getBitWidth()->isValueDependent() ||
8602       Bitfield->getBitWidth()->isTypeDependent() ||
8603       Init->isValueDependent() ||
8604       Init->isTypeDependent())
8605     return false;
8606
8607   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8608
8609   llvm::APSInt Value;
8610   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8611     return false;
8612
8613   unsigned OriginalWidth = Value.getBitWidth();
8614   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8615
8616   if (!Value.isSigned() || Value.isNegative())
8617     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8618       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8619         OriginalWidth = Value.getMinSignedBits();
8620
8621   if (OriginalWidth <= FieldWidth)
8622     return false;
8623
8624   // Compute the value which the bitfield will contain.
8625   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8626   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8627
8628   // Check whether the stored value is equal to the original value.
8629   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8630   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8631     return false;
8632
8633   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8634   // therefore don't strictly fit into a signed bitfield of width 1.
8635   if (FieldWidth == 1 && Value == 1)
8636     return false;
8637
8638   std::string PrettyValue = Value.toString(10);
8639   std::string PrettyTrunc = TruncatedValue.toString(10);
8640
8641   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8642     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8643     << Init->getSourceRange();
8644
8645   return true;
8646 }
8647
8648 /// Analyze the given simple or compound assignment for warning-worthy
8649 /// operations.
8650 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8651   // Just recurse on the LHS.
8652   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8653
8654   // We want to recurse on the RHS as normal unless we're assigning to
8655   // a bitfield.
8656   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8657     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8658                                   E->getOperatorLoc())) {
8659       // Recurse, ignoring any implicit conversions on the RHS.
8660       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8661                                         E->getOperatorLoc());
8662     }
8663   }
8664
8665   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8666 }
8667
8668 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8669 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 
8670                      SourceLocation CContext, unsigned diag,
8671                      bool pruneControlFlow = false) {
8672   if (pruneControlFlow) {
8673     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8674                           S.PDiag(diag)
8675                             << SourceType << T << E->getSourceRange()
8676                             << SourceRange(CContext));
8677     return;
8678   }
8679   S.Diag(E->getExprLoc(), diag)
8680     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8681 }
8682
8683 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8684 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8685                      unsigned diag, bool pruneControlFlow = false) {
8686   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8687 }
8688
8689
8690 /// Diagnose an implicit cast from a floating point value to an integer value.
8691 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8692
8693                              SourceLocation CContext) {
8694   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8695   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8696
8697   Expr *InnerE = E->IgnoreParenImpCasts();
8698   // We also want to warn on, e.g., "int i = -1.234"
8699   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8700     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8701       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8702
8703   const bool IsLiteral =
8704       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8705
8706   llvm::APFloat Value(0.0);
8707   bool IsConstant =
8708     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8709   if (!IsConstant) {
8710     return DiagnoseImpCast(S, E, T, CContext,
8711                            diag::warn_impcast_float_integer, PruneWarnings);
8712   }
8713
8714   bool isExact = false;
8715
8716   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8717                             T->hasUnsignedIntegerRepresentation());
8718   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8719                              &isExact) == llvm::APFloat::opOK &&
8720       isExact) {
8721     if (IsLiteral) return;
8722     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8723                            PruneWarnings);
8724   }
8725
8726   unsigned DiagID = 0;
8727   if (IsLiteral) {
8728     // Warn on floating point literal to integer.
8729     DiagID = diag::warn_impcast_literal_float_to_integer;
8730   } else if (IntegerValue == 0) {
8731     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8732       return DiagnoseImpCast(S, E, T, CContext,
8733                              diag::warn_impcast_float_integer, PruneWarnings);
8734     }
8735     // Warn on non-zero to zero conversion.
8736     DiagID = diag::warn_impcast_float_to_integer_zero;
8737   } else {
8738     if (IntegerValue.isUnsigned()) {
8739       if (!IntegerValue.isMaxValue()) {
8740         return DiagnoseImpCast(S, E, T, CContext,
8741                                diag::warn_impcast_float_integer, PruneWarnings);
8742       }
8743     } else {  // IntegerValue.isSigned()
8744       if (!IntegerValue.isMaxSignedValue() &&
8745           !IntegerValue.isMinSignedValue()) {
8746         return DiagnoseImpCast(S, E, T, CContext,
8747                                diag::warn_impcast_float_integer, PruneWarnings);
8748       }
8749     }
8750     // Warn on evaluatable floating point expression to integer conversion.
8751     DiagID = diag::warn_impcast_float_to_integer;
8752   }
8753
8754   // FIXME: Force the precision of the source value down so we don't print
8755   // digits which are usually useless (we don't really care here if we
8756   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8757   // would automatically print the shortest representation, but it's a bit
8758   // tricky to implement.
8759   SmallString<16> PrettySourceValue;
8760   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8761   precision = (precision * 59 + 195) / 196;
8762   Value.toString(PrettySourceValue, precision);
8763
8764   SmallString<16> PrettyTargetValue;
8765   if (IsBool)
8766     PrettyTargetValue = Value.isZero() ? "false" : "true";
8767   else
8768     IntegerValue.toString(PrettyTargetValue);
8769
8770   if (PruneWarnings) {
8771     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8772                           S.PDiag(DiagID)
8773                               << E->getType() << T.getUnqualifiedType()
8774                               << PrettySourceValue << PrettyTargetValue
8775                               << E->getSourceRange() << SourceRange(CContext));
8776   } else {
8777     S.Diag(E->getExprLoc(), DiagID)
8778         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8779         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8780   }
8781 }
8782
8783 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8784   if (!Range.Width) return "0";
8785
8786   llvm::APSInt ValueInRange = Value;
8787   ValueInRange.setIsSigned(!Range.NonNegative);
8788   ValueInRange = ValueInRange.trunc(Range.Width);
8789   return ValueInRange.toString(10);
8790 }
8791
8792 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8793   if (!isa<ImplicitCastExpr>(Ex))
8794     return false;
8795
8796   Expr *InnerE = Ex->IgnoreParenImpCasts();
8797   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8798   const Type *Source =
8799     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8800   if (Target->isDependentType())
8801     return false;
8802
8803   const BuiltinType *FloatCandidateBT =
8804     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8805   const Type *BoolCandidateType = ToBool ? Target : Source;
8806
8807   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8808           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8809 }
8810
8811 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8812                                       SourceLocation CC) {
8813   unsigned NumArgs = TheCall->getNumArgs();
8814   for (unsigned i = 0; i < NumArgs; ++i) {
8815     Expr *CurrA = TheCall->getArg(i);
8816     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8817       continue;
8818
8819     bool IsSwapped = ((i > 0) &&
8820         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8821     IsSwapped |= ((i < (NumArgs - 1)) &&
8822         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8823     if (IsSwapped) {
8824       // Warn on this floating-point to bool conversion.
8825       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8826                       CurrA->getType(), CC,
8827                       diag::warn_impcast_floating_point_to_bool);
8828     }
8829   }
8830 }
8831
8832 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8833   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8834                         E->getExprLoc()))
8835     return;
8836
8837   // Don't warn on functions which have return type nullptr_t.
8838   if (isa<CallExpr>(E))
8839     return;
8840
8841   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8842   const Expr::NullPointerConstantKind NullKind =
8843       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8844   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8845     return;
8846
8847   // Return if target type is a safe conversion.
8848   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8849       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8850     return;
8851
8852   SourceLocation Loc = E->getSourceRange().getBegin();
8853
8854   // Venture through the macro stacks to get to the source of macro arguments.
8855   // The new location is a better location than the complete location that was
8856   // passed in.
8857   while (S.SourceMgr.isMacroArgExpansion(Loc))
8858     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8859
8860   while (S.SourceMgr.isMacroArgExpansion(CC))
8861     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8862
8863   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8864   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8865     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8866         Loc, S.SourceMgr, S.getLangOpts());
8867     if (MacroName == "NULL")
8868       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8869   }
8870
8871   // Only warn if the null and context location are in the same macro expansion.
8872   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8873     return;
8874
8875   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8876       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8877       << FixItHint::CreateReplacement(Loc,
8878                                       S.getFixItZeroLiteralForType(T, Loc));
8879 }
8880
8881 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8882                            ObjCArrayLiteral *ArrayLiteral);
8883 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8884                                 ObjCDictionaryLiteral *DictionaryLiteral);
8885
8886 /// Check a single element within a collection literal against the
8887 /// target element type.
8888 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8889                                        Expr *Element, unsigned ElementKind) {
8890   // Skip a bitcast to 'id' or qualified 'id'.
8891   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8892     if (ICE->getCastKind() == CK_BitCast &&
8893         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8894       Element = ICE->getSubExpr();
8895   }
8896
8897   QualType ElementType = Element->getType();
8898   ExprResult ElementResult(Element);
8899   if (ElementType->getAs<ObjCObjectPointerType>() &&
8900       S.CheckSingleAssignmentConstraints(TargetElementType,
8901                                          ElementResult,
8902                                          false, false)
8903         != Sema::Compatible) {
8904     S.Diag(Element->getLocStart(),
8905            diag::warn_objc_collection_literal_element)
8906       << ElementType << ElementKind << TargetElementType
8907       << Element->getSourceRange();
8908   }
8909
8910   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8911     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8912   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8913     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8914 }
8915
8916 /// Check an Objective-C array literal being converted to the given
8917 /// target type.
8918 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8919                            ObjCArrayLiteral *ArrayLiteral) {
8920   if (!S.NSArrayDecl)
8921     return;
8922
8923   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8924   if (!TargetObjCPtr)
8925     return;
8926
8927   if (TargetObjCPtr->isUnspecialized() ||
8928       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8929         != S.NSArrayDecl->getCanonicalDecl())
8930     return;
8931
8932   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8933   if (TypeArgs.size() != 1)
8934     return;
8935
8936   QualType TargetElementType = TypeArgs[0];
8937   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8938     checkObjCCollectionLiteralElement(S, TargetElementType,
8939                                       ArrayLiteral->getElement(I),
8940                                       0);
8941   }
8942 }
8943
8944 /// Check an Objective-C dictionary literal being converted to the given
8945 /// target type.
8946 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8947                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8948   if (!S.NSDictionaryDecl)
8949     return;
8950
8951   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8952   if (!TargetObjCPtr)
8953     return;
8954
8955   if (TargetObjCPtr->isUnspecialized() ||
8956       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8957         != S.NSDictionaryDecl->getCanonicalDecl())
8958     return;
8959
8960   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8961   if (TypeArgs.size() != 2)
8962     return;
8963
8964   QualType TargetKeyType = TypeArgs[0];
8965   QualType TargetObjectType = TypeArgs[1];
8966   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8967     auto Element = DictionaryLiteral->getKeyValueElement(I);
8968     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8969     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8970   }
8971 }
8972
8973 // Helper function to filter out cases for constant width constant conversion.
8974 // Don't warn on char array initialization or for non-decimal values.
8975 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8976                                    SourceLocation CC) {
8977   // If initializing from a constant, and the constant starts with '0',
8978   // then it is a binary, octal, or hexadecimal.  Allow these constants
8979   // to fill all the bits, even if there is a sign change.
8980   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8981     const char FirstLiteralCharacter =
8982         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8983     if (FirstLiteralCharacter == '0')
8984       return false;
8985   }
8986
8987   // If the CC location points to a '{', and the type is char, then assume
8988   // assume it is an array initialization.
8989   if (CC.isValid() && T->isCharType()) {
8990     const char FirstContextCharacter =
8991         S.getSourceManager().getCharacterData(CC)[0];
8992     if (FirstContextCharacter == '{')
8993       return false;
8994   }
8995
8996   return true;
8997 }
8998
8999 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9000                              SourceLocation CC, bool *ICContext = nullptr) {
9001   if (E->isTypeDependent() || E->isValueDependent()) return;
9002
9003   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9004   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9005   if (Source == Target) return;
9006   if (Target->isDependentType()) return;
9007
9008   // If the conversion context location is invalid don't complain. We also
9009   // don't want to emit a warning if the issue occurs from the expansion of
9010   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9011   // delay this check as long as possible. Once we detect we are in that
9012   // scenario, we just return.
9013   if (CC.isInvalid())
9014     return;
9015
9016   // Diagnose implicit casts to bool.
9017   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9018     if (isa<StringLiteral>(E))
9019       // Warn on string literal to bool.  Checks for string literals in logical
9020       // and expressions, for instance, assert(0 && "error here"), are
9021       // prevented by a check in AnalyzeImplicitConversions().
9022       return DiagnoseImpCast(S, E, T, CC,
9023                              diag::warn_impcast_string_literal_to_bool);
9024     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9025         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9026       // This covers the literal expressions that evaluate to Objective-C
9027       // objects.
9028       return DiagnoseImpCast(S, E, T, CC,
9029                              diag::warn_impcast_objective_c_literal_to_bool);
9030     }
9031     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9032       // Warn on pointer to bool conversion that is always true.
9033       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9034                                      SourceRange(CC));
9035     }
9036   }
9037
9038   // Check implicit casts from Objective-C collection literals to specialized
9039   // collection types, e.g., NSArray<NSString *> *.
9040   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9041     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9042   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9043     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9044
9045   // Strip vector types.
9046   if (isa<VectorType>(Source)) {
9047     if (!isa<VectorType>(Target)) {
9048       if (S.SourceMgr.isInSystemMacro(CC))
9049         return;
9050       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9051     }
9052     
9053     // If the vector cast is cast between two vectors of the same size, it is
9054     // a bitcast, not a conversion.
9055     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9056       return;
9057
9058     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9059     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9060   }
9061   if (auto VecTy = dyn_cast<VectorType>(Target))
9062     Target = VecTy->getElementType().getTypePtr();
9063
9064   // Strip complex types.
9065   if (isa<ComplexType>(Source)) {
9066     if (!isa<ComplexType>(Target)) {
9067       if (S.SourceMgr.isInSystemMacro(CC))
9068         return;
9069
9070       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9071     }
9072
9073     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9074     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9075   }
9076
9077   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9078   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9079
9080   // If the source is floating point...
9081   if (SourceBT && SourceBT->isFloatingPoint()) {
9082     // ...and the target is floating point...
9083     if (TargetBT && TargetBT->isFloatingPoint()) {
9084       // ...then warn if we're dropping FP rank.
9085
9086       // Builtin FP kinds are ordered by increasing FP rank.
9087       if (SourceBT->getKind() > TargetBT->getKind()) {
9088         // Don't warn about float constants that are precisely
9089         // representable in the target type.
9090         Expr::EvalResult result;
9091         if (E->EvaluateAsRValue(result, S.Context)) {
9092           // Value might be a float, a float vector, or a float complex.
9093           if (IsSameFloatAfterCast(result.Val,
9094                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9095                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9096             return;
9097         }
9098
9099         if (S.SourceMgr.isInSystemMacro(CC))
9100           return;
9101
9102         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9103       }
9104       // ... or possibly if we're increasing rank, too
9105       else if (TargetBT->getKind() > SourceBT->getKind()) {
9106         if (S.SourceMgr.isInSystemMacro(CC))
9107           return;
9108
9109         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9110       }
9111       return;
9112     }
9113
9114     // If the target is integral, always warn.
9115     if (TargetBT && TargetBT->isInteger()) {
9116       if (S.SourceMgr.isInSystemMacro(CC))
9117         return;
9118
9119       DiagnoseFloatingImpCast(S, E, T, CC);
9120     }
9121
9122     // Detect the case where a call result is converted from floating-point to
9123     // to bool, and the final argument to the call is converted from bool, to
9124     // discover this typo:
9125     //
9126     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9127     //
9128     // FIXME: This is an incredibly special case; is there some more general
9129     // way to detect this class of misplaced-parentheses bug?
9130     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9131       // Check last argument of function call to see if it is an
9132       // implicit cast from a type matching the type the result
9133       // is being cast to.
9134       CallExpr *CEx = cast<CallExpr>(E);
9135       if (unsigned NumArgs = CEx->getNumArgs()) {
9136         Expr *LastA = CEx->getArg(NumArgs - 1);
9137         Expr *InnerE = LastA->IgnoreParenImpCasts();
9138         if (isa<ImplicitCastExpr>(LastA) &&
9139             InnerE->getType()->isBooleanType()) {
9140           // Warn on this floating-point to bool conversion
9141           DiagnoseImpCast(S, E, T, CC,
9142                           diag::warn_impcast_floating_point_to_bool);
9143         }
9144       }
9145     }
9146     return;
9147   }
9148
9149   DiagnoseNullConversion(S, E, T, CC);
9150
9151   S.DiscardMisalignedMemberAddress(Target, E);
9152
9153   if (!Source->isIntegerType() || !Target->isIntegerType())
9154     return;
9155
9156   // TODO: remove this early return once the false positives for constant->bool
9157   // in templates, macros, etc, are reduced or removed.
9158   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9159     return;
9160
9161   IntRange SourceRange = GetExprRange(S.Context, E);
9162   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9163
9164   if (SourceRange.Width > TargetRange.Width) {
9165     // If the source is a constant, use a default-on diagnostic.
9166     // TODO: this should happen for bitfield stores, too.
9167     llvm::APSInt Value(32);
9168     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9169       if (S.SourceMgr.isInSystemMacro(CC))
9170         return;
9171
9172       std::string PrettySourceValue = Value.toString(10);
9173       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9174
9175       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9176         S.PDiag(diag::warn_impcast_integer_precision_constant)
9177             << PrettySourceValue << PrettyTargetValue
9178             << E->getType() << T << E->getSourceRange()
9179             << clang::SourceRange(CC));
9180       return;
9181     }
9182
9183     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9184     if (S.SourceMgr.isInSystemMacro(CC))
9185       return;
9186
9187     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9188       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9189                              /* pruneControlFlow */ true);
9190     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9191   }
9192
9193   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9194       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9195     // Warn when doing a signed to signed conversion, warn if the positive
9196     // source value is exactly the width of the target type, which will
9197     // cause a negative value to be stored.
9198
9199     llvm::APSInt Value;
9200     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9201         !S.SourceMgr.isInSystemMacro(CC)) {
9202       if (isSameWidthConstantConversion(S, E, T, CC)) {
9203         std::string PrettySourceValue = Value.toString(10);
9204         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9205
9206         S.DiagRuntimeBehavior(
9207             E->getExprLoc(), E,
9208             S.PDiag(diag::warn_impcast_integer_precision_constant)
9209                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9210                 << E->getSourceRange() << clang::SourceRange(CC));
9211         return;
9212       }
9213     }
9214
9215     // Fall through for non-constants to give a sign conversion warning.
9216   }
9217
9218   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9219       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9220        SourceRange.Width == TargetRange.Width)) {
9221     if (S.SourceMgr.isInSystemMacro(CC))
9222       return;
9223
9224     unsigned DiagID = diag::warn_impcast_integer_sign;
9225
9226     // Traditionally, gcc has warned about this under -Wsign-compare.
9227     // We also want to warn about it in -Wconversion.
9228     // So if -Wconversion is off, use a completely identical diagnostic
9229     // in the sign-compare group.
9230     // The conditional-checking code will 
9231     if (ICContext) {
9232       DiagID = diag::warn_impcast_integer_sign_conditional;
9233       *ICContext = true;
9234     }
9235
9236     return DiagnoseImpCast(S, E, T, CC, DiagID);
9237   }
9238
9239   // Diagnose conversions between different enumeration types.
9240   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9241   // type, to give us better diagnostics.
9242   QualType SourceType = E->getType();
9243   if (!S.getLangOpts().CPlusPlus) {
9244     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9245       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9246         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9247         SourceType = S.Context.getTypeDeclType(Enum);
9248         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9249       }
9250   }
9251   
9252   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9253     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9254       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9255           TargetEnum->getDecl()->hasNameForLinkage() &&
9256           SourceEnum != TargetEnum) {
9257         if (S.SourceMgr.isInSystemMacro(CC))
9258           return;
9259
9260         return DiagnoseImpCast(S, E, SourceType, T, CC, 
9261                                diag::warn_impcast_different_enum_types);
9262       }
9263 }
9264
9265 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9266                               SourceLocation CC, QualType T);
9267
9268 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9269                              SourceLocation CC, bool &ICContext) {
9270   E = E->IgnoreParenImpCasts();
9271
9272   if (isa<ConditionalOperator>(E))
9273     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9274
9275   AnalyzeImplicitConversions(S, E, CC);
9276   if (E->getType() != T)
9277     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9278 }
9279
9280 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9281                               SourceLocation CC, QualType T) {
9282   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9283
9284   bool Suspicious = false;
9285   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9286   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9287
9288   // If -Wconversion would have warned about either of the candidates
9289   // for a signedness conversion to the context type...
9290   if (!Suspicious) return;
9291
9292   // ...but it's currently ignored...
9293   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9294     return;
9295
9296   // ...then check whether it would have warned about either of the
9297   // candidates for a signedness conversion to the condition type.
9298   if (E->getType() == T) return;
9299  
9300   Suspicious = false;
9301   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9302                           E->getType(), CC, &Suspicious);
9303   if (!Suspicious)
9304     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9305                             E->getType(), CC, &Suspicious);
9306 }
9307
9308 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9309 /// Input argument E is a logical expression.
9310 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9311   if (S.getLangOpts().Bool)
9312     return;
9313   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9314 }
9315
9316 /// AnalyzeImplicitConversions - Find and report any interesting
9317 /// implicit conversions in the given expression.  There are a couple
9318 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9319 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9320   QualType T = OrigE->getType();
9321   Expr *E = OrigE->IgnoreParenImpCasts();
9322
9323   if (E->isTypeDependent() || E->isValueDependent())
9324     return;
9325   
9326   // For conditional operators, we analyze the arguments as if they
9327   // were being fed directly into the output.
9328   if (isa<ConditionalOperator>(E)) {
9329     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9330     CheckConditionalOperator(S, CO, CC, T);
9331     return;
9332   }
9333
9334   // Check implicit argument conversions for function calls.
9335   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9336     CheckImplicitArgumentConversions(S, Call, CC);
9337
9338   // Go ahead and check any implicit conversions we might have skipped.
9339   // The non-canonical typecheck is just an optimization;
9340   // CheckImplicitConversion will filter out dead implicit conversions.
9341   if (E->getType() != T)
9342     CheckImplicitConversion(S, E, T, CC);
9343
9344   // Now continue drilling into this expression.
9345
9346   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9347     // The bound subexpressions in a PseudoObjectExpr are not reachable
9348     // as transitive children.
9349     // FIXME: Use a more uniform representation for this.
9350     for (auto *SE : POE->semantics())
9351       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9352         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9353   }
9354
9355   // Skip past explicit casts.
9356   if (isa<ExplicitCastExpr>(E)) {
9357     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9358     return AnalyzeImplicitConversions(S, E, CC);
9359   }
9360
9361   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9362     // Do a somewhat different check with comparison operators.
9363     if (BO->isComparisonOp())
9364       return AnalyzeComparison(S, BO);
9365
9366     // And with simple assignments.
9367     if (BO->getOpcode() == BO_Assign)
9368       return AnalyzeAssignment(S, BO);
9369   }
9370
9371   // These break the otherwise-useful invariant below.  Fortunately,
9372   // we don't really need to recurse into them, because any internal
9373   // expressions should have been analyzed already when they were
9374   // built into statements.
9375   if (isa<StmtExpr>(E)) return;
9376
9377   // Don't descend into unevaluated contexts.
9378   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9379
9380   // Now just recurse over the expression's children.
9381   CC = E->getExprLoc();
9382   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9383   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9384   for (Stmt *SubStmt : E->children()) {
9385     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9386     if (!ChildExpr)
9387       continue;
9388
9389     if (IsLogicalAndOperator &&
9390         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9391       // Ignore checking string literals that are in logical and operators.
9392       // This is a common pattern for asserts.
9393       continue;
9394     AnalyzeImplicitConversions(S, ChildExpr, CC);
9395   }
9396
9397   if (BO && BO->isLogicalOp()) {
9398     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9399     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9400       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9401
9402     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9403     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9404       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9405   }
9406
9407   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9408     if (U->getOpcode() == UO_LNot)
9409       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9410 }
9411
9412 } // end anonymous namespace
9413
9414 /// Diagnose integer type and any valid implicit convertion to it.
9415 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9416   // Taking into account implicit conversions,
9417   // allow any integer.
9418   if (!E->getType()->isIntegerType()) {
9419     S.Diag(E->getLocStart(),
9420            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9421     return true;
9422   }
9423   // Potentially emit standard warnings for implicit conversions if enabled
9424   // using -Wconversion.
9425   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9426   return false;
9427 }
9428
9429 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9430 // Returns true when emitting a warning about taking the address of a reference.
9431 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9432                               const PartialDiagnostic &PD) {
9433   E = E->IgnoreParenImpCasts();
9434
9435   const FunctionDecl *FD = nullptr;
9436
9437   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9438     if (!DRE->getDecl()->getType()->isReferenceType())
9439       return false;
9440   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9441     if (!M->getMemberDecl()->getType()->isReferenceType())
9442       return false;
9443   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9444     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9445       return false;
9446     FD = Call->getDirectCallee();
9447   } else {
9448     return false;
9449   }
9450
9451   SemaRef.Diag(E->getExprLoc(), PD);
9452
9453   // If possible, point to location of function.
9454   if (FD) {
9455     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9456   }
9457
9458   return true;
9459 }
9460
9461 // Returns true if the SourceLocation is expanded from any macro body.
9462 // Returns false if the SourceLocation is invalid, is from not in a macro
9463 // expansion, or is from expanded from a top-level macro argument.
9464 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9465   if (Loc.isInvalid())
9466     return false;
9467
9468   while (Loc.isMacroID()) {
9469     if (SM.isMacroBodyExpansion(Loc))
9470       return true;
9471     Loc = SM.getImmediateMacroCallerLoc(Loc);
9472   }
9473
9474   return false;
9475 }
9476
9477 /// \brief Diagnose pointers that are always non-null.
9478 /// \param E the expression containing the pointer
9479 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9480 /// compared to a null pointer
9481 /// \param IsEqual True when the comparison is equal to a null pointer
9482 /// \param Range Extra SourceRange to highlight in the diagnostic
9483 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9484                                         Expr::NullPointerConstantKind NullKind,
9485                                         bool IsEqual, SourceRange Range) {
9486   if (!E)
9487     return;
9488
9489   // Don't warn inside macros.
9490   if (E->getExprLoc().isMacroID()) {
9491     const SourceManager &SM = getSourceManager();
9492     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9493         IsInAnyMacroBody(SM, Range.getBegin()))
9494       return;
9495   }
9496   E = E->IgnoreImpCasts();
9497
9498   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9499
9500   if (isa<CXXThisExpr>(E)) {
9501     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9502                                 : diag::warn_this_bool_conversion;
9503     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9504     return;
9505   }
9506
9507   bool IsAddressOf = false;
9508
9509   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9510     if (UO->getOpcode() != UO_AddrOf)
9511       return;
9512     IsAddressOf = true;
9513     E = UO->getSubExpr();
9514   }
9515
9516   if (IsAddressOf) {
9517     unsigned DiagID = IsCompare
9518                           ? diag::warn_address_of_reference_null_compare
9519                           : diag::warn_address_of_reference_bool_conversion;
9520     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9521                                          << IsEqual;
9522     if (CheckForReference(*this, E, PD)) {
9523       return;
9524     }
9525   }
9526
9527   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9528     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9529     std::string Str;
9530     llvm::raw_string_ostream S(Str);
9531     E->printPretty(S, nullptr, getPrintingPolicy());
9532     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9533                                 : diag::warn_cast_nonnull_to_bool;
9534     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9535       << E->getSourceRange() << Range << IsEqual;
9536     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9537   };
9538
9539   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9540   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9541     if (auto *Callee = Call->getDirectCallee()) {
9542       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9543         ComplainAboutNonnullParamOrCall(A);
9544         return;
9545       }
9546     }
9547   }
9548
9549   // Expect to find a single Decl.  Skip anything more complicated.
9550   ValueDecl *D = nullptr;
9551   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9552     D = R->getDecl();
9553   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9554     D = M->getMemberDecl();
9555   }
9556
9557   // Weak Decls can be null.
9558   if (!D || D->isWeak())
9559     return;
9560
9561   // Check for parameter decl with nonnull attribute
9562   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9563     if (getCurFunction() &&
9564         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9565       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9566         ComplainAboutNonnullParamOrCall(A);
9567         return;
9568       }
9569
9570       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9571         auto ParamIter = llvm::find(FD->parameters(), PV);
9572         assert(ParamIter != FD->param_end());
9573         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9574
9575         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9576           if (!NonNull->args_size()) {
9577               ComplainAboutNonnullParamOrCall(NonNull);
9578               return;
9579           }
9580
9581           for (unsigned ArgNo : NonNull->args()) {
9582             if (ArgNo == ParamNo) {
9583               ComplainAboutNonnullParamOrCall(NonNull);
9584               return;
9585             }
9586           }
9587         }
9588       }
9589     }
9590   }
9591
9592   QualType T = D->getType();
9593   const bool IsArray = T->isArrayType();
9594   const bool IsFunction = T->isFunctionType();
9595
9596   // Address of function is used to silence the function warning.
9597   if (IsAddressOf && IsFunction) {
9598     return;
9599   }
9600
9601   // Found nothing.
9602   if (!IsAddressOf && !IsFunction && !IsArray)
9603     return;
9604
9605   // Pretty print the expression for the diagnostic.
9606   std::string Str;
9607   llvm::raw_string_ostream S(Str);
9608   E->printPretty(S, nullptr, getPrintingPolicy());
9609
9610   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9611                               : diag::warn_impcast_pointer_to_bool;
9612   enum {
9613     AddressOf,
9614     FunctionPointer,
9615     ArrayPointer
9616   } DiagType;
9617   if (IsAddressOf)
9618     DiagType = AddressOf;
9619   else if (IsFunction)
9620     DiagType = FunctionPointer;
9621   else if (IsArray)
9622     DiagType = ArrayPointer;
9623   else
9624     llvm_unreachable("Could not determine diagnostic.");
9625   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9626                                 << Range << IsEqual;
9627
9628   if (!IsFunction)
9629     return;
9630
9631   // Suggest '&' to silence the function warning.
9632   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9633       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9634
9635   // Check to see if '()' fixit should be emitted.
9636   QualType ReturnType;
9637   UnresolvedSet<4> NonTemplateOverloads;
9638   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9639   if (ReturnType.isNull())
9640     return;
9641
9642   if (IsCompare) {
9643     // There are two cases here.  If there is null constant, the only suggest
9644     // for a pointer return type.  If the null is 0, then suggest if the return
9645     // type is a pointer or an integer type.
9646     if (!ReturnType->isPointerType()) {
9647       if (NullKind == Expr::NPCK_ZeroExpression ||
9648           NullKind == Expr::NPCK_ZeroLiteral) {
9649         if (!ReturnType->isIntegerType())
9650           return;
9651       } else {
9652         return;
9653       }
9654     }
9655   } else { // !IsCompare
9656     // For function to bool, only suggest if the function pointer has bool
9657     // return type.
9658     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9659       return;
9660   }
9661   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9662       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9663 }
9664
9665 /// Diagnoses "dangerous" implicit conversions within the given
9666 /// expression (which is a full expression).  Implements -Wconversion
9667 /// and -Wsign-compare.
9668 ///
9669 /// \param CC the "context" location of the implicit conversion, i.e.
9670 ///   the most location of the syntactic entity requiring the implicit
9671 ///   conversion
9672 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9673   // Don't diagnose in unevaluated contexts.
9674   if (isUnevaluatedContext())
9675     return;
9676
9677   // Don't diagnose for value- or type-dependent expressions.
9678   if (E->isTypeDependent() || E->isValueDependent())
9679     return;
9680
9681   // Check for array bounds violations in cases where the check isn't triggered
9682   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9683   // ArraySubscriptExpr is on the RHS of a variable initialization.
9684   CheckArrayAccess(E);
9685
9686   // This is not the right CC for (e.g.) a variable initialization.
9687   AnalyzeImplicitConversions(*this, E, CC);
9688 }
9689
9690 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9691 /// Input argument E is a logical expression.
9692 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9693   ::CheckBoolLikeConversion(*this, E, CC);
9694 }
9695
9696 /// Diagnose when expression is an integer constant expression and its evaluation
9697 /// results in integer overflow
9698 void Sema::CheckForIntOverflow (Expr *E) {
9699   // Use a work list to deal with nested struct initializers.
9700   SmallVector<Expr *, 2> Exprs(1, E);
9701
9702   do {
9703     Expr *E = Exprs.pop_back_val();
9704
9705     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9706       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9707       continue;
9708     }
9709
9710     if (auto InitList = dyn_cast<InitListExpr>(E))
9711       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9712   } while (!Exprs.empty());
9713 }
9714
9715 namespace {
9716 /// \brief Visitor for expressions which looks for unsequenced operations on the
9717 /// same object.
9718 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9719   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9720
9721   /// \brief A tree of sequenced regions within an expression. Two regions are
9722   /// unsequenced if one is an ancestor or a descendent of the other. When we
9723   /// finish processing an expression with sequencing, such as a comma
9724   /// expression, we fold its tree nodes into its parent, since they are
9725   /// unsequenced with respect to nodes we will visit later.
9726   class SequenceTree {
9727     struct Value {
9728       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9729       unsigned Parent : 31;
9730       unsigned Merged : 1;
9731     };
9732     SmallVector<Value, 8> Values;
9733
9734   public:
9735     /// \brief A region within an expression which may be sequenced with respect
9736     /// to some other region.
9737     class Seq {
9738       explicit Seq(unsigned N) : Index(N) {}
9739       unsigned Index;
9740       friend class SequenceTree;
9741     public:
9742       Seq() : Index(0) {}
9743     };
9744
9745     SequenceTree() { Values.push_back(Value(0)); }
9746     Seq root() const { return Seq(0); }
9747
9748     /// \brief Create a new sequence of operations, which is an unsequenced
9749     /// subset of \p Parent. This sequence of operations is sequenced with
9750     /// respect to other children of \p Parent.
9751     Seq allocate(Seq Parent) {
9752       Values.push_back(Value(Parent.Index));
9753       return Seq(Values.size() - 1);
9754     }
9755
9756     /// \brief Merge a sequence of operations into its parent.
9757     void merge(Seq S) {
9758       Values[S.Index].Merged = true;
9759     }
9760
9761     /// \brief Determine whether two operations are unsequenced. This operation
9762     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9763     /// should have been merged into its parent as appropriate.
9764     bool isUnsequenced(Seq Cur, Seq Old) {
9765       unsigned C = representative(Cur.Index);
9766       unsigned Target = representative(Old.Index);
9767       while (C >= Target) {
9768         if (C == Target)
9769           return true;
9770         C = Values[C].Parent;
9771       }
9772       return false;
9773     }
9774
9775   private:
9776     /// \brief Pick a representative for a sequence.
9777     unsigned representative(unsigned K) {
9778       if (Values[K].Merged)
9779         // Perform path compression as we go.
9780         return Values[K].Parent = representative(Values[K].Parent);
9781       return K;
9782     }
9783   };
9784
9785   /// An object for which we can track unsequenced uses.
9786   typedef NamedDecl *Object;
9787
9788   /// Different flavors of object usage which we track. We only track the
9789   /// least-sequenced usage of each kind.
9790   enum UsageKind {
9791     /// A read of an object. Multiple unsequenced reads are OK.
9792     UK_Use,
9793     /// A modification of an object which is sequenced before the value
9794     /// computation of the expression, such as ++n in C++.
9795     UK_ModAsValue,
9796     /// A modification of an object which is not sequenced before the value
9797     /// computation of the expression, such as n++.
9798     UK_ModAsSideEffect,
9799
9800     UK_Count = UK_ModAsSideEffect + 1
9801   };
9802
9803   struct Usage {
9804     Usage() : Use(nullptr), Seq() {}
9805     Expr *Use;
9806     SequenceTree::Seq Seq;
9807   };
9808
9809   struct UsageInfo {
9810     UsageInfo() : Diagnosed(false) {}
9811     Usage Uses[UK_Count];
9812     /// Have we issued a diagnostic for this variable already?
9813     bool Diagnosed;
9814   };
9815   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9816
9817   Sema &SemaRef;
9818   /// Sequenced regions within the expression.
9819   SequenceTree Tree;
9820   /// Declaration modifications and references which we have seen.
9821   UsageInfoMap UsageMap;
9822   /// The region we are currently within.
9823   SequenceTree::Seq Region;
9824   /// Filled in with declarations which were modified as a side-effect
9825   /// (that is, post-increment operations).
9826   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9827   /// Expressions to check later. We defer checking these to reduce
9828   /// stack usage.
9829   SmallVectorImpl<Expr *> &WorkList;
9830
9831   /// RAII object wrapping the visitation of a sequenced subexpression of an
9832   /// expression. At the end of this process, the side-effects of the evaluation
9833   /// become sequenced with respect to the value computation of the result, so
9834   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9835   /// UK_ModAsValue.
9836   struct SequencedSubexpression {
9837     SequencedSubexpression(SequenceChecker &Self)
9838       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9839       Self.ModAsSideEffect = &ModAsSideEffect;
9840     }
9841     ~SequencedSubexpression() {
9842       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9843         UsageInfo &U = Self.UsageMap[M.first];
9844         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9845         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9846         SideEffectUsage = M.second;
9847       }
9848       Self.ModAsSideEffect = OldModAsSideEffect;
9849     }
9850
9851     SequenceChecker &Self;
9852     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9853     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9854   };
9855
9856   /// RAII object wrapping the visitation of a subexpression which we might
9857   /// choose to evaluate as a constant. If any subexpression is evaluated and
9858   /// found to be non-constant, this allows us to suppress the evaluation of
9859   /// the outer expression.
9860   class EvaluationTracker {
9861   public:
9862     EvaluationTracker(SequenceChecker &Self)
9863         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9864       Self.EvalTracker = this;
9865     }
9866     ~EvaluationTracker() {
9867       Self.EvalTracker = Prev;
9868       if (Prev)
9869         Prev->EvalOK &= EvalOK;
9870     }
9871
9872     bool evaluate(const Expr *E, bool &Result) {
9873       if (!EvalOK || E->isValueDependent())
9874         return false;
9875       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9876       return EvalOK;
9877     }
9878
9879   private:
9880     SequenceChecker &Self;
9881     EvaluationTracker *Prev;
9882     bool EvalOK;
9883   } *EvalTracker;
9884
9885   /// \brief Find the object which is produced by the specified expression,
9886   /// if any.
9887   Object getObject(Expr *E, bool Mod) const {
9888     E = E->IgnoreParenCasts();
9889     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9890       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9891         return getObject(UO->getSubExpr(), Mod);
9892     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9893       if (BO->getOpcode() == BO_Comma)
9894         return getObject(BO->getRHS(), Mod);
9895       if (Mod && BO->isAssignmentOp())
9896         return getObject(BO->getLHS(), Mod);
9897     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9898       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9899       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9900         return ME->getMemberDecl();
9901     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9902       // FIXME: If this is a reference, map through to its value.
9903       return DRE->getDecl();
9904     return nullptr;
9905   }
9906
9907   /// \brief Note that an object was modified or used by an expression.
9908   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9909     Usage &U = UI.Uses[UK];
9910     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9911       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9912         ModAsSideEffect->push_back(std::make_pair(O, U));
9913       U.Use = Ref;
9914       U.Seq = Region;
9915     }
9916   }
9917   /// \brief Check whether a modification or use conflicts with a prior usage.
9918   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9919                   bool IsModMod) {
9920     if (UI.Diagnosed)
9921       return;
9922
9923     const Usage &U = UI.Uses[OtherKind];
9924     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9925       return;
9926
9927     Expr *Mod = U.Use;
9928     Expr *ModOrUse = Ref;
9929     if (OtherKind == UK_Use)
9930       std::swap(Mod, ModOrUse);
9931
9932     SemaRef.Diag(Mod->getExprLoc(),
9933                  IsModMod ? diag::warn_unsequenced_mod_mod
9934                           : diag::warn_unsequenced_mod_use)
9935       << O << SourceRange(ModOrUse->getExprLoc());
9936     UI.Diagnosed = true;
9937   }
9938
9939   void notePreUse(Object O, Expr *Use) {
9940     UsageInfo &U = UsageMap[O];
9941     // Uses conflict with other modifications.
9942     checkUsage(O, U, Use, UK_ModAsValue, false);
9943   }
9944   void notePostUse(Object O, Expr *Use) {
9945     UsageInfo &U = UsageMap[O];
9946     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9947     addUsage(U, O, Use, UK_Use);
9948   }
9949
9950   void notePreMod(Object O, Expr *Mod) {
9951     UsageInfo &U = UsageMap[O];
9952     // Modifications conflict with other modifications and with uses.
9953     checkUsage(O, U, Mod, UK_ModAsValue, true);
9954     checkUsage(O, U, Mod, UK_Use, false);
9955   }
9956   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9957     UsageInfo &U = UsageMap[O];
9958     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9959     addUsage(U, O, Use, UK);
9960   }
9961
9962 public:
9963   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9964       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9965         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9966     Visit(E);
9967   }
9968
9969   void VisitStmt(Stmt *S) {
9970     // Skip all statements which aren't expressions for now.
9971   }
9972
9973   void VisitExpr(Expr *E) {
9974     // By default, just recurse to evaluated subexpressions.
9975     Base::VisitStmt(E);
9976   }
9977
9978   void VisitCastExpr(CastExpr *E) {
9979     Object O = Object();
9980     if (E->getCastKind() == CK_LValueToRValue)
9981       O = getObject(E->getSubExpr(), false);
9982
9983     if (O)
9984       notePreUse(O, E);
9985     VisitExpr(E);
9986     if (O)
9987       notePostUse(O, E);
9988   }
9989
9990   void VisitBinComma(BinaryOperator *BO) {
9991     // C++11 [expr.comma]p1:
9992     //   Every value computation and side effect associated with the left
9993     //   expression is sequenced before every value computation and side
9994     //   effect associated with the right expression.
9995     SequenceTree::Seq LHS = Tree.allocate(Region);
9996     SequenceTree::Seq RHS = Tree.allocate(Region);
9997     SequenceTree::Seq OldRegion = Region;
9998
9999     {
10000       SequencedSubexpression SeqLHS(*this);
10001       Region = LHS;
10002       Visit(BO->getLHS());
10003     }
10004
10005     Region = RHS;
10006     Visit(BO->getRHS());
10007
10008     Region = OldRegion;
10009
10010     // Forget that LHS and RHS are sequenced. They are both unsequenced
10011     // with respect to other stuff.
10012     Tree.merge(LHS);
10013     Tree.merge(RHS);
10014   }
10015
10016   void VisitBinAssign(BinaryOperator *BO) {
10017     // The modification is sequenced after the value computation of the LHS
10018     // and RHS, so check it before inspecting the operands and update the
10019     // map afterwards.
10020     Object O = getObject(BO->getLHS(), true);
10021     if (!O)
10022       return VisitExpr(BO);
10023
10024     notePreMod(O, BO);
10025
10026     // C++11 [expr.ass]p7:
10027     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10028     //   only once.
10029     //
10030     // Therefore, for a compound assignment operator, O is considered used
10031     // everywhere except within the evaluation of E1 itself.
10032     if (isa<CompoundAssignOperator>(BO))
10033       notePreUse(O, BO);
10034
10035     Visit(BO->getLHS());
10036
10037     if (isa<CompoundAssignOperator>(BO))
10038       notePostUse(O, BO);
10039
10040     Visit(BO->getRHS());
10041
10042     // C++11 [expr.ass]p1:
10043     //   the assignment is sequenced [...] before the value computation of the
10044     //   assignment expression.
10045     // C11 6.5.16/3 has no such rule.
10046     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10047                                                        : UK_ModAsSideEffect);
10048   }
10049
10050   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10051     VisitBinAssign(CAO);
10052   }
10053
10054   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10055   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10056   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10057     Object O = getObject(UO->getSubExpr(), true);
10058     if (!O)
10059       return VisitExpr(UO);
10060
10061     notePreMod(O, UO);
10062     Visit(UO->getSubExpr());
10063     // C++11 [expr.pre.incr]p1:
10064     //   the expression ++x is equivalent to x+=1
10065     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10066                                                        : UK_ModAsSideEffect);
10067   }
10068
10069   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10070   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10071   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10072     Object O = getObject(UO->getSubExpr(), true);
10073     if (!O)
10074       return VisitExpr(UO);
10075
10076     notePreMod(O, UO);
10077     Visit(UO->getSubExpr());
10078     notePostMod(O, UO, UK_ModAsSideEffect);
10079   }
10080
10081   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10082   void VisitBinLOr(BinaryOperator *BO) {
10083     // The side-effects of the LHS of an '&&' are sequenced before the
10084     // value computation of the RHS, and hence before the value computation
10085     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10086     // as if they were unconditionally sequenced.
10087     EvaluationTracker Eval(*this);
10088     {
10089       SequencedSubexpression Sequenced(*this);
10090       Visit(BO->getLHS());
10091     }
10092
10093     bool Result;
10094     if (Eval.evaluate(BO->getLHS(), Result)) {
10095       if (!Result)
10096         Visit(BO->getRHS());
10097     } else {
10098       // Check for unsequenced operations in the RHS, treating it as an
10099       // entirely separate evaluation.
10100       //
10101       // FIXME: If there are operations in the RHS which are unsequenced
10102       // with respect to operations outside the RHS, and those operations
10103       // are unconditionally evaluated, diagnose them.
10104       WorkList.push_back(BO->getRHS());
10105     }
10106   }
10107   void VisitBinLAnd(BinaryOperator *BO) {
10108     EvaluationTracker Eval(*this);
10109     {
10110       SequencedSubexpression Sequenced(*this);
10111       Visit(BO->getLHS());
10112     }
10113
10114     bool Result;
10115     if (Eval.evaluate(BO->getLHS(), Result)) {
10116       if (Result)
10117         Visit(BO->getRHS());
10118     } else {
10119       WorkList.push_back(BO->getRHS());
10120     }
10121   }
10122
10123   // Only visit the condition, unless we can be sure which subexpression will
10124   // be chosen.
10125   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10126     EvaluationTracker Eval(*this);
10127     {
10128       SequencedSubexpression Sequenced(*this);
10129       Visit(CO->getCond());
10130     }
10131
10132     bool Result;
10133     if (Eval.evaluate(CO->getCond(), Result))
10134       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10135     else {
10136       WorkList.push_back(CO->getTrueExpr());
10137       WorkList.push_back(CO->getFalseExpr());
10138     }
10139   }
10140
10141   void VisitCallExpr(CallExpr *CE) {
10142     // C++11 [intro.execution]p15:
10143     //   When calling a function [...], every value computation and side effect
10144     //   associated with any argument expression, or with the postfix expression
10145     //   designating the called function, is sequenced before execution of every
10146     //   expression or statement in the body of the function [and thus before
10147     //   the value computation of its result].
10148     SequencedSubexpression Sequenced(*this);
10149     Base::VisitCallExpr(CE);
10150
10151     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10152   }
10153
10154   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10155     // This is a call, so all subexpressions are sequenced before the result.
10156     SequencedSubexpression Sequenced(*this);
10157
10158     if (!CCE->isListInitialization())
10159       return VisitExpr(CCE);
10160
10161     // In C++11, list initializations are sequenced.
10162     SmallVector<SequenceTree::Seq, 32> Elts;
10163     SequenceTree::Seq Parent = Region;
10164     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10165                                         E = CCE->arg_end();
10166          I != E; ++I) {
10167       Region = Tree.allocate(Parent);
10168       Elts.push_back(Region);
10169       Visit(*I);
10170     }
10171
10172     // Forget that the initializers are sequenced.
10173     Region = Parent;
10174     for (unsigned I = 0; I < Elts.size(); ++I)
10175       Tree.merge(Elts[I]);
10176   }
10177
10178   void VisitInitListExpr(InitListExpr *ILE) {
10179     if (!SemaRef.getLangOpts().CPlusPlus11)
10180       return VisitExpr(ILE);
10181
10182     // In C++11, list initializations are sequenced.
10183     SmallVector<SequenceTree::Seq, 32> Elts;
10184     SequenceTree::Seq Parent = Region;
10185     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10186       Expr *E = ILE->getInit(I);
10187       if (!E) continue;
10188       Region = Tree.allocate(Parent);
10189       Elts.push_back(Region);
10190       Visit(E);
10191     }
10192
10193     // Forget that the initializers are sequenced.
10194     Region = Parent;
10195     for (unsigned I = 0; I < Elts.size(); ++I)
10196       Tree.merge(Elts[I]);
10197   }
10198 };
10199 } // end anonymous namespace
10200
10201 void Sema::CheckUnsequencedOperations(Expr *E) {
10202   SmallVector<Expr *, 8> WorkList;
10203   WorkList.push_back(E);
10204   while (!WorkList.empty()) {
10205     Expr *Item = WorkList.pop_back_val();
10206     SequenceChecker(*this, Item, WorkList);
10207   }
10208 }
10209
10210 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10211                               bool IsConstexpr) {
10212   CheckImplicitConversions(E, CheckLoc);
10213   if (!E->isInstantiationDependent())
10214     CheckUnsequencedOperations(E);
10215   if (!IsConstexpr && !E->isValueDependent())
10216     CheckForIntOverflow(E);
10217   DiagnoseMisalignedMembers();
10218 }
10219
10220 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10221                                        FieldDecl *BitField,
10222                                        Expr *Init) {
10223   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10224 }
10225
10226 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10227                                          SourceLocation Loc) {
10228   if (!PType->isVariablyModifiedType())
10229     return;
10230   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10231     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10232     return;
10233   }
10234   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10235     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10236     return;
10237   }
10238   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10239     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10240     return;
10241   }
10242
10243   const ArrayType *AT = S.Context.getAsArrayType(PType);
10244   if (!AT)
10245     return;
10246
10247   if (AT->getSizeModifier() != ArrayType::Star) {
10248     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10249     return;
10250   }
10251
10252   S.Diag(Loc, diag::err_array_star_in_function_definition);
10253 }
10254
10255 /// CheckParmsForFunctionDef - Check that the parameters of the given
10256 /// function are appropriate for the definition of a function. This
10257 /// takes care of any checks that cannot be performed on the
10258 /// declaration itself, e.g., that the types of each of the function
10259 /// parameters are complete.
10260 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10261                                     bool CheckParameterNames) {
10262   bool HasInvalidParm = false;
10263   for (ParmVarDecl *Param : Parameters) {
10264     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10265     // function declarator that is part of a function definition of
10266     // that function shall not have incomplete type.
10267     //
10268     // This is also C++ [dcl.fct]p6.
10269     if (!Param->isInvalidDecl() &&
10270         RequireCompleteType(Param->getLocation(), Param->getType(),
10271                             diag::err_typecheck_decl_incomplete_type)) {
10272       Param->setInvalidDecl();
10273       HasInvalidParm = true;
10274     }
10275
10276     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10277     // declaration of each parameter shall include an identifier.
10278     if (CheckParameterNames &&
10279         Param->getIdentifier() == nullptr &&
10280         !Param->isImplicit() &&
10281         !getLangOpts().CPlusPlus)
10282       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10283
10284     // C99 6.7.5.3p12:
10285     //   If the function declarator is not part of a definition of that
10286     //   function, parameters may have incomplete type and may use the [*]
10287     //   notation in their sequences of declarator specifiers to specify
10288     //   variable length array types.
10289     QualType PType = Param->getOriginalType();
10290     // FIXME: This diagnostic should point the '[*]' if source-location
10291     // information is added for it.
10292     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10293
10294     // MSVC destroys objects passed by value in the callee.  Therefore a
10295     // function definition which takes such a parameter must be able to call the
10296     // object's destructor.  However, we don't perform any direct access check
10297     // on the dtor.
10298     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10299                                        .getCXXABI()
10300                                        .areArgsDestroyedLeftToRightInCallee()) {
10301       if (!Param->isInvalidDecl()) {
10302         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10303           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10304           if (!ClassDecl->isInvalidDecl() &&
10305               !ClassDecl->hasIrrelevantDestructor() &&
10306               !ClassDecl->isDependentContext()) {
10307             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10308             MarkFunctionReferenced(Param->getLocation(), Destructor);
10309             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10310           }
10311         }
10312       }
10313     }
10314
10315     // Parameters with the pass_object_size attribute only need to be marked
10316     // constant at function definitions. Because we lack information about
10317     // whether we're on a declaration or definition when we're instantiating the
10318     // attribute, we need to check for constness here.
10319     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10320       if (!Param->getType().isConstQualified())
10321         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10322             << Attr->getSpelling() << 1;
10323   }
10324
10325   return HasInvalidParm;
10326 }
10327
10328 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10329 /// or MemberExpr.
10330 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10331                               ASTContext &Context) {
10332   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10333     return Context.getDeclAlign(DRE->getDecl());
10334
10335   if (const auto *ME = dyn_cast<MemberExpr>(E))
10336     return Context.getDeclAlign(ME->getMemberDecl());
10337
10338   return TypeAlign;
10339 }
10340
10341 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10342 /// pointer cast increases the alignment requirements.
10343 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10344   // This is actually a lot of work to potentially be doing on every
10345   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10346   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10347     return;
10348
10349   // Ignore dependent types.
10350   if (T->isDependentType() || Op->getType()->isDependentType())
10351     return;
10352
10353   // Require that the destination be a pointer type.
10354   const PointerType *DestPtr = T->getAs<PointerType>();
10355   if (!DestPtr) return;
10356
10357   // If the destination has alignment 1, we're done.
10358   QualType DestPointee = DestPtr->getPointeeType();
10359   if (DestPointee->isIncompleteType()) return;
10360   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10361   if (DestAlign.isOne()) return;
10362
10363   // Require that the source be a pointer type.
10364   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10365   if (!SrcPtr) return;
10366   QualType SrcPointee = SrcPtr->getPointeeType();
10367
10368   // Whitelist casts from cv void*.  We already implicitly
10369   // whitelisted casts to cv void*, since they have alignment 1.
10370   // Also whitelist casts involving incomplete types, which implicitly
10371   // includes 'void'.
10372   if (SrcPointee->isIncompleteType()) return;
10373
10374   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10375
10376   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10377     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10378       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10379   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10380     if (UO->getOpcode() == UO_AddrOf)
10381       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10382   }
10383
10384   if (SrcAlign >= DestAlign) return;
10385
10386   Diag(TRange.getBegin(), diag::warn_cast_align)
10387     << Op->getType() << T
10388     << static_cast<unsigned>(SrcAlign.getQuantity())
10389     << static_cast<unsigned>(DestAlign.getQuantity())
10390     << TRange << Op->getSourceRange();
10391 }
10392
10393 /// \brief Check whether this array fits the idiom of a size-one tail padded
10394 /// array member of a struct.
10395 ///
10396 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10397 /// commonly used to emulate flexible arrays in C89 code.
10398 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10399                                     const NamedDecl *ND) {
10400   if (Size != 1 || !ND) return false;
10401
10402   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10403   if (!FD) return false;
10404
10405   // Don't consider sizes resulting from macro expansions or template argument
10406   // substitution to form C89 tail-padded arrays.
10407
10408   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10409   while (TInfo) {
10410     TypeLoc TL = TInfo->getTypeLoc();
10411     // Look through typedefs.
10412     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10413       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10414       TInfo = TDL->getTypeSourceInfo();
10415       continue;
10416     }
10417     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10418       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10419       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10420         return false;
10421     }
10422     break;
10423   }
10424
10425   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10426   if (!RD) return false;
10427   if (RD->isUnion()) return false;
10428   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10429     if (!CRD->isStandardLayout()) return false;
10430   }
10431
10432   // See if this is the last field decl in the record.
10433   const Decl *D = FD;
10434   while ((D = D->getNextDeclInContext()))
10435     if (isa<FieldDecl>(D))
10436       return false;
10437   return true;
10438 }
10439
10440 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10441                             const ArraySubscriptExpr *ASE,
10442                             bool AllowOnePastEnd, bool IndexNegated) {
10443   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10444   if (IndexExpr->isValueDependent())
10445     return;
10446
10447   const Type *EffectiveType =
10448       BaseExpr->getType()->getPointeeOrArrayElementType();
10449   BaseExpr = BaseExpr->IgnoreParenCasts();
10450   const ConstantArrayType *ArrayTy =
10451     Context.getAsConstantArrayType(BaseExpr->getType());
10452   if (!ArrayTy)
10453     return;
10454
10455   llvm::APSInt index;
10456   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10457     return;
10458   if (IndexNegated)
10459     index = -index;
10460
10461   const NamedDecl *ND = nullptr;
10462   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10463     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10464   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10465     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10466
10467   if (index.isUnsigned() || !index.isNegative()) {
10468     llvm::APInt size = ArrayTy->getSize();
10469     if (!size.isStrictlyPositive())
10470       return;
10471
10472     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10473     if (BaseType != EffectiveType) {
10474       // Make sure we're comparing apples to apples when comparing index to size
10475       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10476       uint64_t array_typesize = Context.getTypeSize(BaseType);
10477       // Handle ptrarith_typesize being zero, such as when casting to void*
10478       if (!ptrarith_typesize) ptrarith_typesize = 1;
10479       if (ptrarith_typesize != array_typesize) {
10480         // There's a cast to a different size type involved
10481         uint64_t ratio = array_typesize / ptrarith_typesize;
10482         // TODO: Be smarter about handling cases where array_typesize is not a
10483         // multiple of ptrarith_typesize
10484         if (ptrarith_typesize * ratio == array_typesize)
10485           size *= llvm::APInt(size.getBitWidth(), ratio);
10486       }
10487     }
10488
10489     if (size.getBitWidth() > index.getBitWidth())
10490       index = index.zext(size.getBitWidth());
10491     else if (size.getBitWidth() < index.getBitWidth())
10492       size = size.zext(index.getBitWidth());
10493
10494     // For array subscripting the index must be less than size, but for pointer
10495     // arithmetic also allow the index (offset) to be equal to size since
10496     // computing the next address after the end of the array is legal and
10497     // commonly done e.g. in C++ iterators and range-based for loops.
10498     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10499       return;
10500
10501     // Also don't warn for arrays of size 1 which are members of some
10502     // structure. These are often used to approximate flexible arrays in C89
10503     // code.
10504     if (IsTailPaddedMemberArray(*this, size, ND))
10505       return;
10506
10507     // Suppress the warning if the subscript expression (as identified by the
10508     // ']' location) and the index expression are both from macro expansions
10509     // within a system header.
10510     if (ASE) {
10511       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10512           ASE->getRBracketLoc());
10513       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10514         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10515             IndexExpr->getLocStart());
10516         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10517           return;
10518       }
10519     }
10520
10521     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10522     if (ASE)
10523       DiagID = diag::warn_array_index_exceeds_bounds;
10524
10525     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10526                         PDiag(DiagID) << index.toString(10, true)
10527                           << size.toString(10, true)
10528                           << (unsigned)size.getLimitedValue(~0U)
10529                           << IndexExpr->getSourceRange());
10530   } else {
10531     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10532     if (!ASE) {
10533       DiagID = diag::warn_ptr_arith_precedes_bounds;
10534       if (index.isNegative()) index = -index;
10535     }
10536
10537     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10538                         PDiag(DiagID) << index.toString(10, true)
10539                           << IndexExpr->getSourceRange());
10540   }
10541
10542   if (!ND) {
10543     // Try harder to find a NamedDecl to point at in the note.
10544     while (const ArraySubscriptExpr *ASE =
10545            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10546       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10547     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10548       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10549     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10550       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10551   }
10552
10553   if (ND)
10554     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10555                         PDiag(diag::note_array_index_out_of_bounds)
10556                           << ND->getDeclName());
10557 }
10558
10559 void Sema::CheckArrayAccess(const Expr *expr) {
10560   int AllowOnePastEnd = 0;
10561   while (expr) {
10562     expr = expr->IgnoreParenImpCasts();
10563     switch (expr->getStmtClass()) {
10564       case Stmt::ArraySubscriptExprClass: {
10565         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10566         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10567                          AllowOnePastEnd > 0);
10568         return;
10569       }
10570       case Stmt::OMPArraySectionExprClass: {
10571         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10572         if (ASE->getLowerBound())
10573           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10574                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10575         return;
10576       }
10577       case Stmt::UnaryOperatorClass: {
10578         // Only unwrap the * and & unary operators
10579         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10580         expr = UO->getSubExpr();
10581         switch (UO->getOpcode()) {
10582           case UO_AddrOf:
10583             AllowOnePastEnd++;
10584             break;
10585           case UO_Deref:
10586             AllowOnePastEnd--;
10587             break;
10588           default:
10589             return;
10590         }
10591         break;
10592       }
10593       case Stmt::ConditionalOperatorClass: {
10594         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10595         if (const Expr *lhs = cond->getLHS())
10596           CheckArrayAccess(lhs);
10597         if (const Expr *rhs = cond->getRHS())
10598           CheckArrayAccess(rhs);
10599         return;
10600       }
10601       default:
10602         return;
10603     }
10604   }
10605 }
10606
10607 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10608
10609 namespace {
10610   struct RetainCycleOwner {
10611     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10612     VarDecl *Variable;
10613     SourceRange Range;
10614     SourceLocation Loc;
10615     bool Indirect;
10616
10617     void setLocsFrom(Expr *e) {
10618       Loc = e->getExprLoc();
10619       Range = e->getSourceRange();
10620     }
10621   };
10622 } // end anonymous namespace
10623
10624 /// Consider whether capturing the given variable can possibly lead to
10625 /// a retain cycle.
10626 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10627   // In ARC, it's captured strongly iff the variable has __strong
10628   // lifetime.  In MRR, it's captured strongly if the variable is
10629   // __block and has an appropriate type.
10630   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10631     return false;
10632
10633   owner.Variable = var;
10634   if (ref)
10635     owner.setLocsFrom(ref);
10636   return true;
10637 }
10638
10639 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10640   while (true) {
10641     e = e->IgnoreParens();
10642     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10643       switch (cast->getCastKind()) {
10644       case CK_BitCast:
10645       case CK_LValueBitCast:
10646       case CK_LValueToRValue:
10647       case CK_ARCReclaimReturnedObject:
10648         e = cast->getSubExpr();
10649         continue;
10650
10651       default:
10652         return false;
10653       }
10654     }
10655
10656     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10657       ObjCIvarDecl *ivar = ref->getDecl();
10658       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10659         return false;
10660
10661       // Try to find a retain cycle in the base.
10662       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10663         return false;
10664
10665       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10666       owner.Indirect = true;
10667       return true;
10668     }
10669
10670     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10671       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10672       if (!var) return false;
10673       return considerVariable(var, ref, owner);
10674     }
10675
10676     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10677       if (member->isArrow()) return false;
10678
10679       // Don't count this as an indirect ownership.
10680       e = member->getBase();
10681       continue;
10682     }
10683
10684     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10685       // Only pay attention to pseudo-objects on property references.
10686       ObjCPropertyRefExpr *pre
10687         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10688                                               ->IgnoreParens());
10689       if (!pre) return false;
10690       if (pre->isImplicitProperty()) return false;
10691       ObjCPropertyDecl *property = pre->getExplicitProperty();
10692       if (!property->isRetaining() &&
10693           !(property->getPropertyIvarDecl() &&
10694             property->getPropertyIvarDecl()->getType()
10695               .getObjCLifetime() == Qualifiers::OCL_Strong))
10696           return false;
10697
10698       owner.Indirect = true;
10699       if (pre->isSuperReceiver()) {
10700         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10701         if (!owner.Variable)
10702           return false;
10703         owner.Loc = pre->getLocation();
10704         owner.Range = pre->getSourceRange();
10705         return true;
10706       }
10707       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10708                               ->getSourceExpr());
10709       continue;
10710     }
10711
10712     // Array ivars?
10713
10714     return false;
10715   }
10716 }
10717
10718 namespace {
10719   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10720     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10721       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10722         Context(Context), Variable(variable), Capturer(nullptr),
10723         VarWillBeReased(false) {}
10724     ASTContext &Context;
10725     VarDecl *Variable;
10726     Expr *Capturer;
10727     bool VarWillBeReased;
10728
10729     void VisitDeclRefExpr(DeclRefExpr *ref) {
10730       if (ref->getDecl() == Variable && !Capturer)
10731         Capturer = ref;
10732     }
10733
10734     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10735       if (Capturer) return;
10736       Visit(ref->getBase());
10737       if (Capturer && ref->isFreeIvar())
10738         Capturer = ref;
10739     }
10740
10741     void VisitBlockExpr(BlockExpr *block) {
10742       // Look inside nested blocks 
10743       if (block->getBlockDecl()->capturesVariable(Variable))
10744         Visit(block->getBlockDecl()->getBody());
10745     }
10746     
10747     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10748       if (Capturer) return;
10749       if (OVE->getSourceExpr())
10750         Visit(OVE->getSourceExpr());
10751     }
10752     void VisitBinaryOperator(BinaryOperator *BinOp) {
10753       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10754         return;
10755       Expr *LHS = BinOp->getLHS();
10756       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10757         if (DRE->getDecl() != Variable)
10758           return;
10759         if (Expr *RHS = BinOp->getRHS()) {
10760           RHS = RHS->IgnoreParenCasts();
10761           llvm::APSInt Value;
10762           VarWillBeReased =
10763             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10764         }
10765       }
10766     }
10767   };
10768 } // end anonymous namespace
10769
10770 /// Check whether the given argument is a block which captures a
10771 /// variable.
10772 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10773   assert(owner.Variable && owner.Loc.isValid());
10774
10775   e = e->IgnoreParenCasts();
10776
10777   // Look through [^{...} copy] and Block_copy(^{...}).
10778   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10779     Selector Cmd = ME->getSelector();
10780     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10781       e = ME->getInstanceReceiver();
10782       if (!e)
10783         return nullptr;
10784       e = e->IgnoreParenCasts();
10785     }
10786   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10787     if (CE->getNumArgs() == 1) {
10788       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10789       if (Fn) {
10790         const IdentifierInfo *FnI = Fn->getIdentifier();
10791         if (FnI && FnI->isStr("_Block_copy")) {
10792           e = CE->getArg(0)->IgnoreParenCasts();
10793         }
10794       }
10795     }
10796   }
10797   
10798   BlockExpr *block = dyn_cast<BlockExpr>(e);
10799   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10800     return nullptr;
10801
10802   FindCaptureVisitor visitor(S.Context, owner.Variable);
10803   visitor.Visit(block->getBlockDecl()->getBody());
10804   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10805 }
10806
10807 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10808                                 RetainCycleOwner &owner) {
10809   assert(capturer);
10810   assert(owner.Variable && owner.Loc.isValid());
10811
10812   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10813     << owner.Variable << capturer->getSourceRange();
10814   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10815     << owner.Indirect << owner.Range;
10816 }
10817
10818 /// Check for a keyword selector that starts with the word 'add' or
10819 /// 'set'.
10820 static bool isSetterLikeSelector(Selector sel) {
10821   if (sel.isUnarySelector()) return false;
10822
10823   StringRef str = sel.getNameForSlot(0);
10824   while (!str.empty() && str.front() == '_') str = str.substr(1);
10825   if (str.startswith("set"))
10826     str = str.substr(3);
10827   else if (str.startswith("add")) {
10828     // Specially whitelist 'addOperationWithBlock:'.
10829     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10830       return false;
10831     str = str.substr(3);
10832   }
10833   else
10834     return false;
10835
10836   if (str.empty()) return true;
10837   return !isLowercase(str.front());
10838 }
10839
10840 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10841                                                     ObjCMessageExpr *Message) {
10842   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10843                                                 Message->getReceiverInterface(),
10844                                                 NSAPI::ClassId_NSMutableArray);
10845   if (!IsMutableArray) {
10846     return None;
10847   }
10848
10849   Selector Sel = Message->getSelector();
10850
10851   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10852     S.NSAPIObj->getNSArrayMethodKind(Sel);
10853   if (!MKOpt) {
10854     return None;
10855   }
10856
10857   NSAPI::NSArrayMethodKind MK = *MKOpt;
10858
10859   switch (MK) {
10860     case NSAPI::NSMutableArr_addObject:
10861     case NSAPI::NSMutableArr_insertObjectAtIndex:
10862     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10863       return 0;
10864     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10865       return 1;
10866
10867     default:
10868       return None;
10869   }
10870
10871   return None;
10872 }
10873
10874 static
10875 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10876                                                   ObjCMessageExpr *Message) {
10877   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10878                                             Message->getReceiverInterface(),
10879                                             NSAPI::ClassId_NSMutableDictionary);
10880   if (!IsMutableDictionary) {
10881     return None;
10882   }
10883
10884   Selector Sel = Message->getSelector();
10885
10886   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10887     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10888   if (!MKOpt) {
10889     return None;
10890   }
10891
10892   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10893
10894   switch (MK) {
10895     case NSAPI::NSMutableDict_setObjectForKey:
10896     case NSAPI::NSMutableDict_setValueForKey:
10897     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10898       return 0;
10899
10900     default:
10901       return None;
10902   }
10903
10904   return None;
10905 }
10906
10907 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10908   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10909                                                 Message->getReceiverInterface(),
10910                                                 NSAPI::ClassId_NSMutableSet);
10911
10912   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10913                                             Message->getReceiverInterface(),
10914                                             NSAPI::ClassId_NSMutableOrderedSet);
10915   if (!IsMutableSet && !IsMutableOrderedSet) {
10916     return None;
10917   }
10918
10919   Selector Sel = Message->getSelector();
10920
10921   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10922   if (!MKOpt) {
10923     return None;
10924   }
10925
10926   NSAPI::NSSetMethodKind MK = *MKOpt;
10927
10928   switch (MK) {
10929     case NSAPI::NSMutableSet_addObject:
10930     case NSAPI::NSOrderedSet_setObjectAtIndex:
10931     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10932     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10933       return 0;
10934     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10935       return 1;
10936   }
10937
10938   return None;
10939 }
10940
10941 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10942   if (!Message->isInstanceMessage()) {
10943     return;
10944   }
10945
10946   Optional<int> ArgOpt;
10947
10948   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10949       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10950       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10951     return;
10952   }
10953
10954   int ArgIndex = *ArgOpt;
10955
10956   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10957   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10958     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10959   }
10960
10961   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10962     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10963       if (ArgRE->isObjCSelfExpr()) {
10964         Diag(Message->getSourceRange().getBegin(),
10965              diag::warn_objc_circular_container)
10966           << ArgRE->getDecl()->getName() << StringRef("super");
10967       }
10968     }
10969   } else {
10970     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10971
10972     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10973       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10974     }
10975
10976     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10977       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10978         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10979           ValueDecl *Decl = ReceiverRE->getDecl();
10980           Diag(Message->getSourceRange().getBegin(),
10981                diag::warn_objc_circular_container)
10982             << Decl->getName() << Decl->getName();
10983           if (!ArgRE->isObjCSelfExpr()) {
10984             Diag(Decl->getLocation(),
10985                  diag::note_objc_circular_container_declared_here)
10986               << Decl->getName();
10987           }
10988         }
10989       }
10990     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10991       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10992         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10993           ObjCIvarDecl *Decl = IvarRE->getDecl();
10994           Diag(Message->getSourceRange().getBegin(),
10995                diag::warn_objc_circular_container)
10996             << Decl->getName() << Decl->getName();
10997           Diag(Decl->getLocation(),
10998                diag::note_objc_circular_container_declared_here)
10999             << Decl->getName();
11000         }
11001       }
11002     }
11003   }
11004 }
11005
11006 /// Check a message send to see if it's likely to cause a retain cycle.
11007 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11008   // Only check instance methods whose selector looks like a setter.
11009   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11010     return;
11011
11012   // Try to find a variable that the receiver is strongly owned by.
11013   RetainCycleOwner owner;
11014   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11015     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11016       return;
11017   } else {
11018     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11019     owner.Variable = getCurMethodDecl()->getSelfDecl();
11020     owner.Loc = msg->getSuperLoc();
11021     owner.Range = msg->getSuperLoc();
11022   }
11023
11024   // Check whether the receiver is captured by any of the arguments.
11025   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11026     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11027       return diagnoseRetainCycle(*this, capturer, owner);
11028 }
11029
11030 /// Check a property assign to see if it's likely to cause a retain cycle.
11031 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11032   RetainCycleOwner owner;
11033   if (!findRetainCycleOwner(*this, receiver, owner))
11034     return;
11035
11036   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11037     diagnoseRetainCycle(*this, capturer, owner);
11038 }
11039
11040 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11041   RetainCycleOwner Owner;
11042   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11043     return;
11044   
11045   // Because we don't have an expression for the variable, we have to set the
11046   // location explicitly here.
11047   Owner.Loc = Var->getLocation();
11048   Owner.Range = Var->getSourceRange();
11049   
11050   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11051     diagnoseRetainCycle(*this, Capturer, Owner);
11052 }
11053
11054 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11055                                      Expr *RHS, bool isProperty) {
11056   // Check if RHS is an Objective-C object literal, which also can get
11057   // immediately zapped in a weak reference.  Note that we explicitly
11058   // allow ObjCStringLiterals, since those are designed to never really die.
11059   RHS = RHS->IgnoreParenImpCasts();
11060
11061   // This enum needs to match with the 'select' in
11062   // warn_objc_arc_literal_assign (off-by-1).
11063   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11064   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11065     return false;
11066
11067   S.Diag(Loc, diag::warn_arc_literal_assign)
11068     << (unsigned) Kind
11069     << (isProperty ? 0 : 1)
11070     << RHS->getSourceRange();
11071
11072   return true;
11073 }
11074
11075 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11076                                     Qualifiers::ObjCLifetime LT,
11077                                     Expr *RHS, bool isProperty) {
11078   // Strip off any implicit cast added to get to the one ARC-specific.
11079   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11080     if (cast->getCastKind() == CK_ARCConsumeObject) {
11081       S.Diag(Loc, diag::warn_arc_retained_assign)
11082         << (LT == Qualifiers::OCL_ExplicitNone)
11083         << (isProperty ? 0 : 1)
11084         << RHS->getSourceRange();
11085       return true;
11086     }
11087     RHS = cast->getSubExpr();
11088   }
11089
11090   if (LT == Qualifiers::OCL_Weak &&
11091       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11092     return true;
11093
11094   return false;
11095 }
11096
11097 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11098                               QualType LHS, Expr *RHS) {
11099   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11100
11101   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11102     return false;
11103
11104   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11105     return true;
11106
11107   return false;
11108 }
11109
11110 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11111                               Expr *LHS, Expr *RHS) {
11112   QualType LHSType;
11113   // PropertyRef on LHS type need be directly obtained from
11114   // its declaration as it has a PseudoType.
11115   ObjCPropertyRefExpr *PRE
11116     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11117   if (PRE && !PRE->isImplicitProperty()) {
11118     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11119     if (PD)
11120       LHSType = PD->getType();
11121   }
11122   
11123   if (LHSType.isNull())
11124     LHSType = LHS->getType();
11125
11126   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11127
11128   if (LT == Qualifiers::OCL_Weak) {
11129     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11130       getCurFunction()->markSafeWeakUse(LHS);
11131   }
11132
11133   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11134     return;
11135
11136   // FIXME. Check for other life times.
11137   if (LT != Qualifiers::OCL_None)
11138     return;
11139   
11140   if (PRE) {
11141     if (PRE->isImplicitProperty())
11142       return;
11143     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11144     if (!PD)
11145       return;
11146     
11147     unsigned Attributes = PD->getPropertyAttributes();
11148     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11149       // when 'assign' attribute was not explicitly specified
11150       // by user, ignore it and rely on property type itself
11151       // for lifetime info.
11152       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11153       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11154           LHSType->isObjCRetainableType())
11155         return;
11156         
11157       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11158         if (cast->getCastKind() == CK_ARCConsumeObject) {
11159           Diag(Loc, diag::warn_arc_retained_property_assign)
11160           << RHS->getSourceRange();
11161           return;
11162         }
11163         RHS = cast->getSubExpr();
11164       }
11165     }
11166     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11167       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11168         return;
11169     }
11170   }
11171 }
11172
11173 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11174
11175 namespace {
11176 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11177                                  SourceLocation StmtLoc,
11178                                  const NullStmt *Body) {
11179   // Do not warn if the body is a macro that expands to nothing, e.g:
11180   //
11181   // #define CALL(x)
11182   // if (condition)
11183   //   CALL(0);
11184   //
11185   if (Body->hasLeadingEmptyMacro())
11186     return false;
11187
11188   // Get line numbers of statement and body.
11189   bool StmtLineInvalid;
11190   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11191                                                       &StmtLineInvalid);
11192   if (StmtLineInvalid)
11193     return false;
11194
11195   bool BodyLineInvalid;
11196   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11197                                                       &BodyLineInvalid);
11198   if (BodyLineInvalid)
11199     return false;
11200
11201   // Warn if null statement and body are on the same line.
11202   if (StmtLine != BodyLine)
11203     return false;
11204
11205   return true;
11206 }
11207 } // end anonymous namespace
11208
11209 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11210                                  const Stmt *Body,
11211                                  unsigned DiagID) {
11212   // Since this is a syntactic check, don't emit diagnostic for template
11213   // instantiations, this just adds noise.
11214   if (CurrentInstantiationScope)
11215     return;
11216
11217   // The body should be a null statement.
11218   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11219   if (!NBody)
11220     return;
11221
11222   // Do the usual checks.
11223   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11224     return;
11225
11226   Diag(NBody->getSemiLoc(), DiagID);
11227   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11228 }
11229
11230 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11231                                  const Stmt *PossibleBody) {
11232   assert(!CurrentInstantiationScope); // Ensured by caller
11233
11234   SourceLocation StmtLoc;
11235   const Stmt *Body;
11236   unsigned DiagID;
11237   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11238     StmtLoc = FS->getRParenLoc();
11239     Body = FS->getBody();
11240     DiagID = diag::warn_empty_for_body;
11241   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11242     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11243     Body = WS->getBody();
11244     DiagID = diag::warn_empty_while_body;
11245   } else
11246     return; // Neither `for' nor `while'.
11247
11248   // The body should be a null statement.
11249   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11250   if (!NBody)
11251     return;
11252
11253   // Skip expensive checks if diagnostic is disabled.
11254   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11255     return;
11256
11257   // Do the usual checks.
11258   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11259     return;
11260
11261   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11262   // noise level low, emit diagnostics only if for/while is followed by a
11263   // CompoundStmt, e.g.:
11264   //    for (int i = 0; i < n; i++);
11265   //    {
11266   //      a(i);
11267   //    }
11268   // or if for/while is followed by a statement with more indentation
11269   // than for/while itself:
11270   //    for (int i = 0; i < n; i++);
11271   //      a(i);
11272   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11273   if (!ProbableTypo) {
11274     bool BodyColInvalid;
11275     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11276                              PossibleBody->getLocStart(),
11277                              &BodyColInvalid);
11278     if (BodyColInvalid)
11279       return;
11280
11281     bool StmtColInvalid;
11282     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11283                              S->getLocStart(),
11284                              &StmtColInvalid);
11285     if (StmtColInvalid)
11286       return;
11287
11288     if (BodyCol > StmtCol)
11289       ProbableTypo = true;
11290   }
11291
11292   if (ProbableTypo) {
11293     Diag(NBody->getSemiLoc(), DiagID);
11294     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11295   }
11296 }
11297
11298 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11299
11300 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11301 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11302                              SourceLocation OpLoc) {
11303   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11304     return;
11305
11306   if (!ActiveTemplateInstantiations.empty())
11307     return;
11308
11309   // Strip parens and casts away.
11310   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11311   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11312
11313   // Check for a call expression
11314   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11315   if (!CE || CE->getNumArgs() != 1)
11316     return;
11317
11318   // Check for a call to std::move
11319   const FunctionDecl *FD = CE->getDirectCallee();
11320   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11321       !FD->getIdentifier()->isStr("move"))
11322     return;
11323
11324   // Get argument from std::move
11325   RHSExpr = CE->getArg(0);
11326
11327   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11328   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11329
11330   // Two DeclRefExpr's, check that the decls are the same.
11331   if (LHSDeclRef && RHSDeclRef) {
11332     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11333       return;
11334     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11335         RHSDeclRef->getDecl()->getCanonicalDecl())
11336       return;
11337
11338     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11339                                         << LHSExpr->getSourceRange()
11340                                         << RHSExpr->getSourceRange();
11341     return;
11342   }
11343
11344   // Member variables require a different approach to check for self moves.
11345   // MemberExpr's are the same if every nested MemberExpr refers to the same
11346   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11347   // the base Expr's are CXXThisExpr's.
11348   const Expr *LHSBase = LHSExpr;
11349   const Expr *RHSBase = RHSExpr;
11350   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11351   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11352   if (!LHSME || !RHSME)
11353     return;
11354
11355   while (LHSME && RHSME) {
11356     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11357         RHSME->getMemberDecl()->getCanonicalDecl())
11358       return;
11359
11360     LHSBase = LHSME->getBase();
11361     RHSBase = RHSME->getBase();
11362     LHSME = dyn_cast<MemberExpr>(LHSBase);
11363     RHSME = dyn_cast<MemberExpr>(RHSBase);
11364   }
11365
11366   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11367   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11368   if (LHSDeclRef && RHSDeclRef) {
11369     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11370       return;
11371     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11372         RHSDeclRef->getDecl()->getCanonicalDecl())
11373       return;
11374
11375     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11376                                         << LHSExpr->getSourceRange()
11377                                         << RHSExpr->getSourceRange();
11378     return;
11379   }
11380
11381   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11382     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11383                                         << LHSExpr->getSourceRange()
11384                                         << RHSExpr->getSourceRange();
11385 }
11386
11387 //===--- Layout compatibility ----------------------------------------------//
11388
11389 namespace {
11390
11391 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11392
11393 /// \brief Check if two enumeration types are layout-compatible.
11394 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11395   // C++11 [dcl.enum] p8:
11396   // Two enumeration types are layout-compatible if they have the same
11397   // underlying type.
11398   return ED1->isComplete() && ED2->isComplete() &&
11399          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11400 }
11401
11402 /// \brief Check if two fields are layout-compatible.
11403 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11404   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11405     return false;
11406
11407   if (Field1->isBitField() != Field2->isBitField())
11408     return false;
11409
11410   if (Field1->isBitField()) {
11411     // Make sure that the bit-fields are the same length.
11412     unsigned Bits1 = Field1->getBitWidthValue(C);
11413     unsigned Bits2 = Field2->getBitWidthValue(C);
11414
11415     if (Bits1 != Bits2)
11416       return false;
11417   }
11418
11419   return true;
11420 }
11421
11422 /// \brief Check if two standard-layout structs are layout-compatible.
11423 /// (C++11 [class.mem] p17)
11424 bool isLayoutCompatibleStruct(ASTContext &C,
11425                               RecordDecl *RD1,
11426                               RecordDecl *RD2) {
11427   // If both records are C++ classes, check that base classes match.
11428   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11429     // If one of records is a CXXRecordDecl we are in C++ mode,
11430     // thus the other one is a CXXRecordDecl, too.
11431     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11432     // Check number of base classes.
11433     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11434       return false;
11435
11436     // Check the base classes.
11437     for (CXXRecordDecl::base_class_const_iterator
11438                Base1 = D1CXX->bases_begin(),
11439            BaseEnd1 = D1CXX->bases_end(),
11440               Base2 = D2CXX->bases_begin();
11441          Base1 != BaseEnd1;
11442          ++Base1, ++Base2) {
11443       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11444         return false;
11445     }
11446   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11447     // If only RD2 is a C++ class, it should have zero base classes.
11448     if (D2CXX->getNumBases() > 0)
11449       return false;
11450   }
11451
11452   // Check the fields.
11453   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11454                              Field2End = RD2->field_end(),
11455                              Field1 = RD1->field_begin(),
11456                              Field1End = RD1->field_end();
11457   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11458     if (!isLayoutCompatible(C, *Field1, *Field2))
11459       return false;
11460   }
11461   if (Field1 != Field1End || Field2 != Field2End)
11462     return false;
11463
11464   return true;
11465 }
11466
11467 /// \brief Check if two standard-layout unions are layout-compatible.
11468 /// (C++11 [class.mem] p18)
11469 bool isLayoutCompatibleUnion(ASTContext &C,
11470                              RecordDecl *RD1,
11471                              RecordDecl *RD2) {
11472   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11473   for (auto *Field2 : RD2->fields())
11474     UnmatchedFields.insert(Field2);
11475
11476   for (auto *Field1 : RD1->fields()) {
11477     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11478         I = UnmatchedFields.begin(),
11479         E = UnmatchedFields.end();
11480
11481     for ( ; I != E; ++I) {
11482       if (isLayoutCompatible(C, Field1, *I)) {
11483         bool Result = UnmatchedFields.erase(*I);
11484         (void) Result;
11485         assert(Result);
11486         break;
11487       }
11488     }
11489     if (I == E)
11490       return false;
11491   }
11492
11493   return UnmatchedFields.empty();
11494 }
11495
11496 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11497   if (RD1->isUnion() != RD2->isUnion())
11498     return false;
11499
11500   if (RD1->isUnion())
11501     return isLayoutCompatibleUnion(C, RD1, RD2);
11502   else
11503     return isLayoutCompatibleStruct(C, RD1, RD2);
11504 }
11505
11506 /// \brief Check if two types are layout-compatible in C++11 sense.
11507 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11508   if (T1.isNull() || T2.isNull())
11509     return false;
11510
11511   // C++11 [basic.types] p11:
11512   // If two types T1 and T2 are the same type, then T1 and T2 are
11513   // layout-compatible types.
11514   if (C.hasSameType(T1, T2))
11515     return true;
11516
11517   T1 = T1.getCanonicalType().getUnqualifiedType();
11518   T2 = T2.getCanonicalType().getUnqualifiedType();
11519
11520   const Type::TypeClass TC1 = T1->getTypeClass();
11521   const Type::TypeClass TC2 = T2->getTypeClass();
11522
11523   if (TC1 != TC2)
11524     return false;
11525
11526   if (TC1 == Type::Enum) {
11527     return isLayoutCompatible(C,
11528                               cast<EnumType>(T1)->getDecl(),
11529                               cast<EnumType>(T2)->getDecl());
11530   } else if (TC1 == Type::Record) {
11531     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11532       return false;
11533
11534     return isLayoutCompatible(C,
11535                               cast<RecordType>(T1)->getDecl(),
11536                               cast<RecordType>(T2)->getDecl());
11537   }
11538
11539   return false;
11540 }
11541 } // end anonymous namespace
11542
11543 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11544
11545 namespace {
11546 /// \brief Given a type tag expression find the type tag itself.
11547 ///
11548 /// \param TypeExpr Type tag expression, as it appears in user's code.
11549 ///
11550 /// \param VD Declaration of an identifier that appears in a type tag.
11551 ///
11552 /// \param MagicValue Type tag magic value.
11553 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11554                      const ValueDecl **VD, uint64_t *MagicValue) {
11555   while(true) {
11556     if (!TypeExpr)
11557       return false;
11558
11559     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11560
11561     switch (TypeExpr->getStmtClass()) {
11562     case Stmt::UnaryOperatorClass: {
11563       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11564       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11565         TypeExpr = UO->getSubExpr();
11566         continue;
11567       }
11568       return false;
11569     }
11570
11571     case Stmt::DeclRefExprClass: {
11572       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11573       *VD = DRE->getDecl();
11574       return true;
11575     }
11576
11577     case Stmt::IntegerLiteralClass: {
11578       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11579       llvm::APInt MagicValueAPInt = IL->getValue();
11580       if (MagicValueAPInt.getActiveBits() <= 64) {
11581         *MagicValue = MagicValueAPInt.getZExtValue();
11582         return true;
11583       } else
11584         return false;
11585     }
11586
11587     case Stmt::BinaryConditionalOperatorClass:
11588     case Stmt::ConditionalOperatorClass: {
11589       const AbstractConditionalOperator *ACO =
11590           cast<AbstractConditionalOperator>(TypeExpr);
11591       bool Result;
11592       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11593         if (Result)
11594           TypeExpr = ACO->getTrueExpr();
11595         else
11596           TypeExpr = ACO->getFalseExpr();
11597         continue;
11598       }
11599       return false;
11600     }
11601
11602     case Stmt::BinaryOperatorClass: {
11603       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11604       if (BO->getOpcode() == BO_Comma) {
11605         TypeExpr = BO->getRHS();
11606         continue;
11607       }
11608       return false;
11609     }
11610
11611     default:
11612       return false;
11613     }
11614   }
11615 }
11616
11617 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11618 ///
11619 /// \param TypeExpr Expression that specifies a type tag.
11620 ///
11621 /// \param MagicValues Registered magic values.
11622 ///
11623 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11624 ///        kind.
11625 ///
11626 /// \param TypeInfo Information about the corresponding C type.
11627 ///
11628 /// \returns true if the corresponding C type was found.
11629 bool GetMatchingCType(
11630         const IdentifierInfo *ArgumentKind,
11631         const Expr *TypeExpr, const ASTContext &Ctx,
11632         const llvm::DenseMap<Sema::TypeTagMagicValue,
11633                              Sema::TypeTagData> *MagicValues,
11634         bool &FoundWrongKind,
11635         Sema::TypeTagData &TypeInfo) {
11636   FoundWrongKind = false;
11637
11638   // Variable declaration that has type_tag_for_datatype attribute.
11639   const ValueDecl *VD = nullptr;
11640
11641   uint64_t MagicValue;
11642
11643   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11644     return false;
11645
11646   if (VD) {
11647     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11648       if (I->getArgumentKind() != ArgumentKind) {
11649         FoundWrongKind = true;
11650         return false;
11651       }
11652       TypeInfo.Type = I->getMatchingCType();
11653       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11654       TypeInfo.MustBeNull = I->getMustBeNull();
11655       return true;
11656     }
11657     return false;
11658   }
11659
11660   if (!MagicValues)
11661     return false;
11662
11663   llvm::DenseMap<Sema::TypeTagMagicValue,
11664                  Sema::TypeTagData>::const_iterator I =
11665       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11666   if (I == MagicValues->end())
11667     return false;
11668
11669   TypeInfo = I->second;
11670   return true;
11671 }
11672 } // end anonymous namespace
11673
11674 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11675                                       uint64_t MagicValue, QualType Type,
11676                                       bool LayoutCompatible,
11677                                       bool MustBeNull) {
11678   if (!TypeTagForDatatypeMagicValues)
11679     TypeTagForDatatypeMagicValues.reset(
11680         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11681
11682   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11683   (*TypeTagForDatatypeMagicValues)[Magic] =
11684       TypeTagData(Type, LayoutCompatible, MustBeNull);
11685 }
11686
11687 namespace {
11688 bool IsSameCharType(QualType T1, QualType T2) {
11689   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11690   if (!BT1)
11691     return false;
11692
11693   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11694   if (!BT2)
11695     return false;
11696
11697   BuiltinType::Kind T1Kind = BT1->getKind();
11698   BuiltinType::Kind T2Kind = BT2->getKind();
11699
11700   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11701          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11702          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11703          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11704 }
11705 } // end anonymous namespace
11706
11707 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11708                                     const Expr * const *ExprArgs) {
11709   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11710   bool IsPointerAttr = Attr->getIsPointer();
11711
11712   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11713   bool FoundWrongKind;
11714   TypeTagData TypeInfo;
11715   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11716                         TypeTagForDatatypeMagicValues.get(),
11717                         FoundWrongKind, TypeInfo)) {
11718     if (FoundWrongKind)
11719       Diag(TypeTagExpr->getExprLoc(),
11720            diag::warn_type_tag_for_datatype_wrong_kind)
11721         << TypeTagExpr->getSourceRange();
11722     return;
11723   }
11724
11725   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11726   if (IsPointerAttr) {
11727     // Skip implicit cast of pointer to `void *' (as a function argument).
11728     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11729       if (ICE->getType()->isVoidPointerType() &&
11730           ICE->getCastKind() == CK_BitCast)
11731         ArgumentExpr = ICE->getSubExpr();
11732   }
11733   QualType ArgumentType = ArgumentExpr->getType();
11734
11735   // Passing a `void*' pointer shouldn't trigger a warning.
11736   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11737     return;
11738
11739   if (TypeInfo.MustBeNull) {
11740     // Type tag with matching void type requires a null pointer.
11741     if (!ArgumentExpr->isNullPointerConstant(Context,
11742                                              Expr::NPC_ValueDependentIsNotNull)) {
11743       Diag(ArgumentExpr->getExprLoc(),
11744            diag::warn_type_safety_null_pointer_required)
11745           << ArgumentKind->getName()
11746           << ArgumentExpr->getSourceRange()
11747           << TypeTagExpr->getSourceRange();
11748     }
11749     return;
11750   }
11751
11752   QualType RequiredType = TypeInfo.Type;
11753   if (IsPointerAttr)
11754     RequiredType = Context.getPointerType(RequiredType);
11755
11756   bool mismatch = false;
11757   if (!TypeInfo.LayoutCompatible) {
11758     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11759
11760     // C++11 [basic.fundamental] p1:
11761     // Plain char, signed char, and unsigned char are three distinct types.
11762     //
11763     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11764     // char' depending on the current char signedness mode.
11765     if (mismatch)
11766       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11767                                            RequiredType->getPointeeType())) ||
11768           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11769         mismatch = false;
11770   } else
11771     if (IsPointerAttr)
11772       mismatch = !isLayoutCompatible(Context,
11773                                      ArgumentType->getPointeeType(),
11774                                      RequiredType->getPointeeType());
11775     else
11776       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11777
11778   if (mismatch)
11779     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11780         << ArgumentType << ArgumentKind
11781         << TypeInfo.LayoutCompatible << RequiredType
11782         << ArgumentExpr->getSourceRange()
11783         << TypeTagExpr->getSourceRange();
11784 }
11785
11786 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11787                                          CharUnits Alignment) {
11788   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11789 }
11790
11791 void Sema::DiagnoseMisalignedMembers() {
11792   for (MisalignedMember &m : MisalignedMembers) {
11793     const NamedDecl *ND = m.RD;
11794     if (ND->getName().empty()) {
11795       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11796         ND = TD;
11797     }
11798     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11799         << m.MD << ND << m.E->getSourceRange();
11800   }
11801   MisalignedMembers.clear();
11802 }
11803
11804 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11805   E = E->IgnoreParens();
11806   if (!T->isPointerType() && !T->isIntegerType())
11807     return;
11808   if (isa<UnaryOperator>(E) &&
11809       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11810     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11811     if (isa<MemberExpr>(Op)) {
11812       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11813                           MisalignedMember(Op));
11814       if (MA != MisalignedMembers.end() &&
11815           (T->isIntegerType() ||
11816            (T->isPointerType() &&
11817             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
11818         MisalignedMembers.erase(MA);
11819     }
11820   }
11821 }
11822
11823 void Sema::RefersToMemberWithReducedAlignment(
11824     Expr *E,
11825     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11826         Action) {
11827   const auto *ME = dyn_cast<MemberExpr>(E);
11828   if (!ME)
11829     return;
11830
11831   // For a chain of MemberExpr like "a.b.c.d" this list
11832   // will keep FieldDecl's like [d, c, b].
11833   SmallVector<FieldDecl *, 4> ReverseMemberChain;
11834   const MemberExpr *TopME = nullptr;
11835   bool AnyIsPacked = false;
11836   do {
11837     QualType BaseType = ME->getBase()->getType();
11838     if (ME->isArrow())
11839       BaseType = BaseType->getPointeeType();
11840     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11841
11842     ValueDecl *MD = ME->getMemberDecl();
11843     auto *FD = dyn_cast<FieldDecl>(MD);
11844     // We do not care about non-data members.
11845     if (!FD || FD->isInvalidDecl())
11846       return;
11847
11848     AnyIsPacked =
11849         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11850     ReverseMemberChain.push_back(FD);
11851
11852     TopME = ME;
11853     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11854   } while (ME);
11855   assert(TopME && "We did not compute a topmost MemberExpr!");
11856
11857   // Not the scope of this diagnostic.
11858   if (!AnyIsPacked)
11859     return;
11860
11861   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11862   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11863   // TODO: The innermost base of the member expression may be too complicated.
11864   // For now, just disregard these cases. This is left for future
11865   // improvement.
11866   if (!DRE && !isa<CXXThisExpr>(TopBase))
11867       return;
11868
11869   // Alignment expected by the whole expression.
11870   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11871
11872   // No need to do anything else with this case.
11873   if (ExpectedAlignment.isOne())
11874     return;
11875
11876   // Synthesize offset of the whole access.
11877   CharUnits Offset;
11878   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11879        I++) {
11880     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11881   }
11882
11883   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11884   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11885       ReverseMemberChain.back()->getParent()->getTypeForDecl());
11886
11887   // The base expression of the innermost MemberExpr may give
11888   // stronger guarantees than the class containing the member.
11889   if (DRE && !TopME->isArrow()) {
11890     const ValueDecl *VD = DRE->getDecl();
11891     if (!VD->getType()->isReferenceType())
11892       CompleteObjectAlignment =
11893           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11894   }
11895
11896   // Check if the synthesized offset fulfills the alignment.
11897   if (Offset % ExpectedAlignment != 0 ||
11898       // It may fulfill the offset it but the effective alignment may still be
11899       // lower than the expected expression alignment.
11900       CompleteObjectAlignment < ExpectedAlignment) {
11901     // If this happens, we want to determine a sensible culprit of this.
11902     // Intuitively, watching the chain of member expressions from right to
11903     // left, we start with the required alignment (as required by the field
11904     // type) but some packed attribute in that chain has reduced the alignment.
11905     // It may happen that another packed structure increases it again. But if
11906     // we are here such increase has not been enough. So pointing the first
11907     // FieldDecl that either is packed or else its RecordDecl is,
11908     // seems reasonable.
11909     FieldDecl *FD = nullptr;
11910     CharUnits Alignment;
11911     for (FieldDecl *FDI : ReverseMemberChain) {
11912       if (FDI->hasAttr<PackedAttr>() ||
11913           FDI->getParent()->hasAttr<PackedAttr>()) {
11914         FD = FDI;
11915         Alignment = std::min(
11916             Context.getTypeAlignInChars(FD->getType()),
11917             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11918         break;
11919       }
11920     }
11921     assert(FD && "We did not find a packed FieldDecl!");
11922     Action(E, FD->getParent(), FD, Alignment);
11923   }
11924 }
11925
11926 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11927   using namespace std::placeholders;
11928   RefersToMemberWithReducedAlignment(
11929       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11930                      _2, _3, _4));
11931 }
11932