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