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