1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCXXABI.h"
14 #include "CGCleanup.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "ConstantEmitter.h"
20 #include "TargetInfo.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/Basic/CodeGenOptions.h"
27 #include "clang/Basic/FixedPoint.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Module.h"
38 #include <cstdarg>
39 
40 using namespace clang;
41 using namespace CodeGen;
42 using llvm::Value;
43 
44 //===----------------------------------------------------------------------===//
45 //                         Scalar Expression Emitter
46 //===----------------------------------------------------------------------===//
47 
48 namespace {
49 
50 /// Determine whether the given binary operation may overflow.
51 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
52 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
53 /// the returned overflow check is precise. The returned value is 'true' for
54 /// all other opcodes, to be conservative.
55 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
56                              BinaryOperator::Opcode Opcode, bool Signed,
57                              llvm::APInt &Result) {
58   // Assume overflow is possible, unless we can prove otherwise.
59   bool Overflow = true;
60   const auto &LHSAP = LHS->getValue();
61   const auto &RHSAP = RHS->getValue();
62   if (Opcode == BO_Add) {
63     if (Signed)
64       Result = LHSAP.sadd_ov(RHSAP, Overflow);
65     else
66       Result = LHSAP.uadd_ov(RHSAP, Overflow);
67   } else if (Opcode == BO_Sub) {
68     if (Signed)
69       Result = LHSAP.ssub_ov(RHSAP, Overflow);
70     else
71       Result = LHSAP.usub_ov(RHSAP, Overflow);
72   } else if (Opcode == BO_Mul) {
73     if (Signed)
74       Result = LHSAP.smul_ov(RHSAP, Overflow);
75     else
76       Result = LHSAP.umul_ov(RHSAP, Overflow);
77   } else if (Opcode == BO_Div || Opcode == BO_Rem) {
78     if (Signed && !RHS->isZero())
79       Result = LHSAP.sdiv_ov(RHSAP, Overflow);
80     else
81       return false;
82   }
83   return Overflow;
84 }
85 
86 struct BinOpInfo {
87   Value *LHS;
88   Value *RHS;
89   QualType Ty;  // Computation Type.
90   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
91   FPOptions FPFeatures;
92   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
93 
94   /// Check if the binop can result in integer overflow.
95   bool mayHaveIntegerOverflow() const {
96     // Without constant input, we can't rule out overflow.
97     auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
98     auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
99     if (!LHSCI || !RHSCI)
100       return true;
101 
102     llvm::APInt Result;
103     return ::mayHaveIntegerOverflow(
104         LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
105   }
106 
107   /// Check if the binop computes a division or a remainder.
108   bool isDivremOp() const {
109     return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
110            Opcode == BO_RemAssign;
111   }
112 
113   /// Check if the binop can result in an integer division by zero.
114   bool mayHaveIntegerDivisionByZero() const {
115     if (isDivremOp())
116       if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
117         return CI->isZero();
118     return true;
119   }
120 
121   /// Check if the binop can result in a float division by zero.
122   bool mayHaveFloatDivisionByZero() const {
123     if (isDivremOp())
124       if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
125         return CFP->isZero();
126     return true;
127   }
128 
129   /// Check if either operand is a fixed point type or integer type, with at
130   /// least one being a fixed point type. In any case, this
131   /// operation did not follow usual arithmetic conversion and both operands may
132   /// not be the same.
133   bool isFixedPointBinOp() const {
134     // We cannot simply check the result type since comparison operations return
135     // an int.
136     if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
137       QualType LHSType = BinOp->getLHS()->getType();
138       QualType RHSType = BinOp->getRHS()->getType();
139       return LHSType->isFixedPointType() || RHSType->isFixedPointType();
140     }
141     return false;
142   }
143 };
144 
145 static bool MustVisitNullValue(const Expr *E) {
146   // If a null pointer expression's type is the C++0x nullptr_t, then
147   // it's not necessarily a simple constant and it must be evaluated
148   // for its potential side effects.
149   return E->getType()->isNullPtrType();
150 }
151 
152 /// If \p E is a widened promoted integer, get its base (unpromoted) type.
153 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
154                                                         const Expr *E) {
155   const Expr *Base = E->IgnoreImpCasts();
156   if (E == Base)
157     return llvm::None;
158 
159   QualType BaseTy = Base->getType();
160   if (!BaseTy->isPromotableIntegerType() ||
161       Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
162     return llvm::None;
163 
164   return BaseTy;
165 }
166 
167 /// Check if \p E is a widened promoted integer.
168 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
169   return getUnwidenedIntegerType(Ctx, E).hasValue();
170 }
171 
172 /// Check if we can skip the overflow check for \p Op.
173 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
174   assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
175          "Expected a unary or binary operator");
176 
177   // If the binop has constant inputs and we can prove there is no overflow,
178   // we can elide the overflow check.
179   if (!Op.mayHaveIntegerOverflow())
180     return true;
181 
182   // If a unary op has a widened operand, the op cannot overflow.
183   if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
184     return !UO->canOverflow();
185 
186   // We usually don't need overflow checks for binops with widened operands.
187   // Multiplication with promoted unsigned operands is a special case.
188   const auto *BO = cast<BinaryOperator>(Op.E);
189   auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
190   if (!OptionalLHSTy)
191     return false;
192 
193   auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
194   if (!OptionalRHSTy)
195     return false;
196 
197   QualType LHSTy = *OptionalLHSTy;
198   QualType RHSTy = *OptionalRHSTy;
199 
200   // This is the simple case: binops without unsigned multiplication, and with
201   // widened operands. No overflow check is needed here.
202   if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
203       !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
204     return true;
205 
206   // For unsigned multiplication the overflow check can be elided if either one
207   // of the unpromoted types are less than half the size of the promoted type.
208   unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
209   return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
210          (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
211 }
212 
213 /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
214 static void updateFastMathFlags(llvm::FastMathFlags &FMF,
215                                 FPOptions FPFeatures) {
216   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
217 }
218 
219 /// Propagate fast-math flags from \p Op to the instruction in \p V.
220 static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
221   if (auto *I = dyn_cast<llvm::Instruction>(V)) {
222     llvm::FastMathFlags FMF = I->getFastMathFlags();
223     updateFastMathFlags(FMF, Op.FPFeatures);
224     I->setFastMathFlags(FMF);
225   }
226   return V;
227 }
228 
229 class ScalarExprEmitter
230   : public StmtVisitor<ScalarExprEmitter, Value*> {
231   CodeGenFunction &CGF;
232   CGBuilderTy &Builder;
233   bool IgnoreResultAssign;
234   llvm::LLVMContext &VMContext;
235 public:
236 
237   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
238     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
239       VMContext(cgf.getLLVMContext()) {
240   }
241 
242   //===--------------------------------------------------------------------===//
243   //                               Utilities
244   //===--------------------------------------------------------------------===//
245 
246   bool TestAndClearIgnoreResultAssign() {
247     bool I = IgnoreResultAssign;
248     IgnoreResultAssign = false;
249     return I;
250   }
251 
252   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
253   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
254   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
255     return CGF.EmitCheckedLValue(E, TCK);
256   }
257 
258   void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
259                       const BinOpInfo &Info);
260 
261   Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
262     return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
263   }
264 
265   void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
266     const AlignValueAttr *AVAttr = nullptr;
267     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
268       const ValueDecl *VD = DRE->getDecl();
269 
270       if (VD->getType()->isReferenceType()) {
271         if (const auto *TTy =
272             dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
273           AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
274       } else {
275         // Assumptions for function parameters are emitted at the start of the
276         // function, so there is no need to repeat that here,
277         // unless the alignment-assumption sanitizer is enabled,
278         // then we prefer the assumption over alignment attribute
279         // on IR function param.
280         if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
281           return;
282 
283         AVAttr = VD->getAttr<AlignValueAttr>();
284       }
285     }
286 
287     if (!AVAttr)
288       if (const auto *TTy =
289           dyn_cast<TypedefType>(E->getType()))
290         AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
291 
292     if (!AVAttr)
293       return;
294 
295     Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
296     llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
297     CGF.EmitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
298   }
299 
300   /// EmitLoadOfLValue - Given an expression with complex type that represents a
301   /// value l-value, this method emits the address of the l-value, then loads
302   /// and returns the result.
303   Value *EmitLoadOfLValue(const Expr *E) {
304     Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
305                                 E->getExprLoc());
306 
307     EmitLValueAlignmentAssumption(E, V);
308     return V;
309   }
310 
311   /// EmitConversionToBool - Convert the specified expression value to a
312   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
313   Value *EmitConversionToBool(Value *Src, QualType DstTy);
314 
315   /// Emit a check that a conversion from a floating-point type does not
316   /// overflow.
317   void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
318                                 Value *Src, QualType SrcType, QualType DstType,
319                                 llvm::Type *DstTy, SourceLocation Loc);
320 
321   /// Known implicit conversion check kinds.
322   /// Keep in sync with the enum of the same name in ubsan_handlers.h
323   enum ImplicitConversionCheckKind : unsigned char {
324     ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
325     ICCK_UnsignedIntegerTruncation = 1,
326     ICCK_SignedIntegerTruncation = 2,
327     ICCK_IntegerSignChange = 3,
328     ICCK_SignedIntegerTruncationOrSignChange = 4,
329   };
330 
331   /// Emit a check that an [implicit] truncation of an integer  does not
332   /// discard any bits. It is not UB, so we use the value after truncation.
333   void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
334                                   QualType DstType, SourceLocation Loc);
335 
336   /// Emit a check that an [implicit] conversion of an integer does not change
337   /// the sign of the value. It is not UB, so we use the value after conversion.
338   /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
339   void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
340                                   QualType DstType, SourceLocation Loc);
341 
342   /// Emit a conversion from the specified type to the specified destination
343   /// type, both of which are LLVM scalar types.
344   struct ScalarConversionOpts {
345     bool TreatBooleanAsSigned;
346     bool EmitImplicitIntegerTruncationChecks;
347     bool EmitImplicitIntegerSignChangeChecks;
348 
349     ScalarConversionOpts()
350         : TreatBooleanAsSigned(false),
351           EmitImplicitIntegerTruncationChecks(false),
352           EmitImplicitIntegerSignChangeChecks(false) {}
353 
354     ScalarConversionOpts(clang::SanitizerSet SanOpts)
355         : TreatBooleanAsSigned(false),
356           EmitImplicitIntegerTruncationChecks(
357               SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
358           EmitImplicitIntegerSignChangeChecks(
359               SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
360   };
361   Value *
362   EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
363                        SourceLocation Loc,
364                        ScalarConversionOpts Opts = ScalarConversionOpts());
365 
366   /// Convert between either a fixed point and other fixed point or fixed point
367   /// and an integer.
368   Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
369                                   SourceLocation Loc);
370   Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
371                                   FixedPointSemantics &DstFixedSema,
372                                   SourceLocation Loc,
373                                   bool DstIsInteger = false);
374 
375   /// Emit a conversion from the specified complex type to the specified
376   /// destination type, where the destination type is an LLVM scalar type.
377   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
378                                        QualType SrcTy, QualType DstTy,
379                                        SourceLocation Loc);
380 
381   /// EmitNullValue - Emit a value that corresponds to null for the given type.
382   Value *EmitNullValue(QualType Ty);
383 
384   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
385   Value *EmitFloatToBoolConversion(Value *V) {
386     // Compare against 0.0 for fp scalars.
387     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
388     return Builder.CreateFCmpUNE(V, Zero, "tobool");
389   }
390 
391   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
392   Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
393     Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
394 
395     return Builder.CreateICmpNE(V, Zero, "tobool");
396   }
397 
398   Value *EmitIntToBoolConversion(Value *V) {
399     // Because of the type rules of C, we often end up computing a
400     // logical value, then zero extending it to int, then wanting it
401     // as a logical value again.  Optimize this common case.
402     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
403       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
404         Value *Result = ZI->getOperand(0);
405         // If there aren't any more uses, zap the instruction to save space.
406         // Note that there can be more uses, for example if this
407         // is the result of an assignment.
408         if (ZI->use_empty())
409           ZI->eraseFromParent();
410         return Result;
411       }
412     }
413 
414     return Builder.CreateIsNotNull(V, "tobool");
415   }
416 
417   //===--------------------------------------------------------------------===//
418   //                            Visitor Methods
419   //===--------------------------------------------------------------------===//
420 
421   Value *Visit(Expr *E) {
422     ApplyDebugLocation DL(CGF, E);
423     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
424   }
425 
426   Value *VisitStmt(Stmt *S) {
427     S->dump(CGF.getContext().getSourceManager());
428     llvm_unreachable("Stmt can't have complex result type!");
429   }
430   Value *VisitExpr(Expr *S);
431 
432   Value *VisitConstantExpr(ConstantExpr *E) {
433     return Visit(E->getSubExpr());
434   }
435   Value *VisitParenExpr(ParenExpr *PE) {
436     return Visit(PE->getSubExpr());
437   }
438   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
439     return Visit(E->getReplacement());
440   }
441   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
442     return Visit(GE->getResultExpr());
443   }
444   Value *VisitCoawaitExpr(CoawaitExpr *S) {
445     return CGF.EmitCoawaitExpr(*S).getScalarVal();
446   }
447   Value *VisitCoyieldExpr(CoyieldExpr *S) {
448     return CGF.EmitCoyieldExpr(*S).getScalarVal();
449   }
450   Value *VisitUnaryCoawait(const UnaryOperator *E) {
451     return Visit(E->getSubExpr());
452   }
453 
454   // Leaves.
455   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
456     return Builder.getInt(E->getValue());
457   }
458   Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
459     return Builder.getInt(E->getValue());
460   }
461   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
462     return llvm::ConstantFP::get(VMContext, E->getValue());
463   }
464   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
465     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
466   }
467   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
468     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
469   }
470   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
471     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
472   }
473   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
474     return EmitNullValue(E->getType());
475   }
476   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
477     return EmitNullValue(E->getType());
478   }
479   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
480   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
481   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
482     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
483     return Builder.CreateBitCast(V, ConvertType(E->getType()));
484   }
485 
486   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
487     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
488   }
489 
490   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
491     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
492   }
493 
494   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
495     if (E->isGLValue())
496       return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
497                               E->getExprLoc());
498 
499     // Otherwise, assume the mapping is the scalar directly.
500     return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
501   }
502 
503   // l-values.
504   Value *VisitDeclRefExpr(DeclRefExpr *E) {
505     if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
506       return CGF.emitScalarConstant(Constant, E);
507     return EmitLoadOfLValue(E);
508   }
509 
510   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
511     return CGF.EmitObjCSelectorExpr(E);
512   }
513   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
514     return CGF.EmitObjCProtocolExpr(E);
515   }
516   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
517     return EmitLoadOfLValue(E);
518   }
519   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
520     if (E->getMethodDecl() &&
521         E->getMethodDecl()->getReturnType()->isReferenceType())
522       return EmitLoadOfLValue(E);
523     return CGF.EmitObjCMessageExpr(E).getScalarVal();
524   }
525 
526   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
527     LValue LV = CGF.EmitObjCIsaExpr(E);
528     Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
529     return V;
530   }
531 
532   Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
533     VersionTuple Version = E->getVersion();
534 
535     // If we're checking for a platform older than our minimum deployment
536     // target, we can fold the check away.
537     if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
538       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
539 
540     Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
541     llvm::Value *Args[] = {
542         llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
543         llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
544         llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
545     };
546 
547     return CGF.EmitBuiltinAvailable(Args);
548   }
549 
550   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
551   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
552   Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
553   Value *VisitMemberExpr(MemberExpr *E);
554   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
555   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
556     return EmitLoadOfLValue(E);
557   }
558 
559   Value *VisitInitListExpr(InitListExpr *E);
560 
561   Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
562     assert(CGF.getArrayInitIndex() &&
563            "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
564     return CGF.getArrayInitIndex();
565   }
566 
567   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
568     return EmitNullValue(E->getType());
569   }
570   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
571     CGF.CGM.EmitExplicitCastExprType(E, &CGF);
572     return VisitCastExpr(E);
573   }
574   Value *VisitCastExpr(CastExpr *E);
575 
576   Value *VisitCallExpr(const CallExpr *E) {
577     if (E->getCallReturnType(CGF.getContext())->isReferenceType())
578       return EmitLoadOfLValue(E);
579 
580     Value *V = CGF.EmitCallExpr(E).getScalarVal();
581 
582     EmitLValueAlignmentAssumption(E, V);
583     return V;
584   }
585 
586   Value *VisitStmtExpr(const StmtExpr *E);
587 
588   // Unary Operators.
589   Value *VisitUnaryPostDec(const UnaryOperator *E) {
590     LValue LV = EmitLValue(E->getSubExpr());
591     return EmitScalarPrePostIncDec(E, LV, false, false);
592   }
593   Value *VisitUnaryPostInc(const UnaryOperator *E) {
594     LValue LV = EmitLValue(E->getSubExpr());
595     return EmitScalarPrePostIncDec(E, LV, true, false);
596   }
597   Value *VisitUnaryPreDec(const UnaryOperator *E) {
598     LValue LV = EmitLValue(E->getSubExpr());
599     return EmitScalarPrePostIncDec(E, LV, false, true);
600   }
601   Value *VisitUnaryPreInc(const UnaryOperator *E) {
602     LValue LV = EmitLValue(E->getSubExpr());
603     return EmitScalarPrePostIncDec(E, LV, true, true);
604   }
605 
606   llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
607                                                   llvm::Value *InVal,
608                                                   bool IsInc);
609 
610   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
611                                        bool isInc, bool isPre);
612 
613 
614   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
615     if (isa<MemberPointerType>(E->getType())) // never sugared
616       return CGF.CGM.getMemberPointerConstant(E);
617 
618     return EmitLValue(E->getSubExpr()).getPointer();
619   }
620   Value *VisitUnaryDeref(const UnaryOperator *E) {
621     if (E->getType()->isVoidType())
622       return Visit(E->getSubExpr()); // the actual value should be unused
623     return EmitLoadOfLValue(E);
624   }
625   Value *VisitUnaryPlus(const UnaryOperator *E) {
626     // This differs from gcc, though, most likely due to a bug in gcc.
627     TestAndClearIgnoreResultAssign();
628     return Visit(E->getSubExpr());
629   }
630   Value *VisitUnaryMinus    (const UnaryOperator *E);
631   Value *VisitUnaryNot      (const UnaryOperator *E);
632   Value *VisitUnaryLNot     (const UnaryOperator *E);
633   Value *VisitUnaryReal     (const UnaryOperator *E);
634   Value *VisitUnaryImag     (const UnaryOperator *E);
635   Value *VisitUnaryExtension(const UnaryOperator *E) {
636     return Visit(E->getSubExpr());
637   }
638 
639   // C++
640   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
641     return EmitLoadOfLValue(E);
642   }
643   Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
644     auto &Ctx = CGF.getContext();
645     APValue Evaluated =
646         SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
647     return ConstantEmitter(CGF.CGM, &CGF)
648         .emitAbstract(SLE->getLocation(), Evaluated, SLE->getType());
649   }
650 
651   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
652     CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
653     return Visit(DAE->getExpr());
654   }
655   Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
656     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
657     return Visit(DIE->getExpr());
658   }
659   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
660     return CGF.LoadCXXThis();
661   }
662 
663   Value *VisitExprWithCleanups(ExprWithCleanups *E);
664   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
665     return CGF.EmitCXXNewExpr(E);
666   }
667   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
668     CGF.EmitCXXDeleteExpr(E);
669     return nullptr;
670   }
671 
672   Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
673     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
674   }
675 
676   Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
677     return Builder.getInt1(E->isSatisfied());
678   }
679 
680   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
681     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
682   }
683 
684   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
685     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
686   }
687 
688   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
689     // C++ [expr.pseudo]p1:
690     //   The result shall only be used as the operand for the function call
691     //   operator (), and the result of such a call has type void. The only
692     //   effect is the evaluation of the postfix-expression before the dot or
693     //   arrow.
694     CGF.EmitScalarExpr(E->getBase());
695     return nullptr;
696   }
697 
698   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
699     return EmitNullValue(E->getType());
700   }
701 
702   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
703     CGF.EmitCXXThrowExpr(E);
704     return nullptr;
705   }
706 
707   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
708     return Builder.getInt1(E->getValue());
709   }
710 
711   // Binary Operators.
712   Value *EmitMul(const BinOpInfo &Ops) {
713     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
714       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
715       case LangOptions::SOB_Defined:
716         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
717       case LangOptions::SOB_Undefined:
718         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
719           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
720         LLVM_FALLTHROUGH;
721       case LangOptions::SOB_Trapping:
722         if (CanElideOverflowCheck(CGF.getContext(), Ops))
723           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
724         return EmitOverflowCheckedBinOp(Ops);
725       }
726     }
727 
728     if (Ops.Ty->isUnsignedIntegerType() &&
729         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
730         !CanElideOverflowCheck(CGF.getContext(), Ops))
731       return EmitOverflowCheckedBinOp(Ops);
732 
733     if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
734       Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
735       return propagateFMFlags(V, Ops);
736     }
737     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
738   }
739   /// Create a binary op that checks for overflow.
740   /// Currently only supports +, - and *.
741   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
742 
743   // Check for undefined division and modulus behaviors.
744   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
745                                                   llvm::Value *Zero,bool isDiv);
746   // Common helper for getting how wide LHS of shift is.
747   static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
748   Value *EmitDiv(const BinOpInfo &Ops);
749   Value *EmitRem(const BinOpInfo &Ops);
750   Value *EmitAdd(const BinOpInfo &Ops);
751   Value *EmitSub(const BinOpInfo &Ops);
752   Value *EmitShl(const BinOpInfo &Ops);
753   Value *EmitShr(const BinOpInfo &Ops);
754   Value *EmitAnd(const BinOpInfo &Ops) {
755     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
756   }
757   Value *EmitXor(const BinOpInfo &Ops) {
758     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
759   }
760   Value *EmitOr (const BinOpInfo &Ops) {
761     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
762   }
763 
764   // Helper functions for fixed point binary operations.
765   Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
766 
767   BinOpInfo EmitBinOps(const BinaryOperator *E);
768   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
769                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
770                                   Value *&Result);
771 
772   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
773                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
774 
775   // Binary operators and binary compound assignment operators.
776 #define HANDLEBINOP(OP) \
777   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
778     return Emit ## OP(EmitBinOps(E));                                      \
779   }                                                                        \
780   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
781     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
782   }
783   HANDLEBINOP(Mul)
784   HANDLEBINOP(Div)
785   HANDLEBINOP(Rem)
786   HANDLEBINOP(Add)
787   HANDLEBINOP(Sub)
788   HANDLEBINOP(Shl)
789   HANDLEBINOP(Shr)
790   HANDLEBINOP(And)
791   HANDLEBINOP(Xor)
792   HANDLEBINOP(Or)
793 #undef HANDLEBINOP
794 
795   // Comparisons.
796   Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
797                      llvm::CmpInst::Predicate SICmpOpc,
798                      llvm::CmpInst::Predicate FCmpOpc);
799 #define VISITCOMP(CODE, UI, SI, FP) \
800     Value *VisitBin##CODE(const BinaryOperator *E) { \
801       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
802                          llvm::FCmpInst::FP); }
803   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
804   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
805   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
806   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
807   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
808   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
809 #undef VISITCOMP
810 
811   Value *VisitBinAssign     (const BinaryOperator *E);
812 
813   Value *VisitBinLAnd       (const BinaryOperator *E);
814   Value *VisitBinLOr        (const BinaryOperator *E);
815   Value *VisitBinComma      (const BinaryOperator *E);
816 
817   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
818   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
819 
820   // Other Operators.
821   Value *VisitBlockExpr(const BlockExpr *BE);
822   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
823   Value *VisitChooseExpr(ChooseExpr *CE);
824   Value *VisitVAArgExpr(VAArgExpr *VE);
825   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
826     return CGF.EmitObjCStringLiteral(E);
827   }
828   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
829     return CGF.EmitObjCBoxedExpr(E);
830   }
831   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
832     return CGF.EmitObjCArrayLiteral(E);
833   }
834   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
835     return CGF.EmitObjCDictionaryLiteral(E);
836   }
837   Value *VisitAsTypeExpr(AsTypeExpr *CE);
838   Value *VisitAtomicExpr(AtomicExpr *AE);
839 };
840 }  // end anonymous namespace.
841 
842 //===----------------------------------------------------------------------===//
843 //                                Utilities
844 //===----------------------------------------------------------------------===//
845 
846 /// EmitConversionToBool - Convert the specified expression value to a
847 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
848 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
849   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
850 
851   if (SrcType->isRealFloatingType())
852     return EmitFloatToBoolConversion(Src);
853 
854   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
855     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
856 
857   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
858          "Unknown scalar type to convert");
859 
860   if (isa<llvm::IntegerType>(Src->getType()))
861     return EmitIntToBoolConversion(Src);
862 
863   assert(isa<llvm::PointerType>(Src->getType()));
864   return EmitPointerToBoolConversion(Src, SrcType);
865 }
866 
867 void ScalarExprEmitter::EmitFloatConversionCheck(
868     Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
869     QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
870   assert(SrcType->isFloatingType() && "not a conversion from floating point");
871   if (!isa<llvm::IntegerType>(DstTy))
872     return;
873 
874   CodeGenFunction::SanitizerScope SanScope(&CGF);
875   using llvm::APFloat;
876   using llvm::APSInt;
877 
878   llvm::Value *Check = nullptr;
879   const llvm::fltSemantics &SrcSema =
880     CGF.getContext().getFloatTypeSemantics(OrigSrcType);
881 
882   // Floating-point to integer. This has undefined behavior if the source is
883   // +-Inf, NaN, or doesn't fit into the destination type (after truncation
884   // to an integer).
885   unsigned Width = CGF.getContext().getIntWidth(DstType);
886   bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
887 
888   APSInt Min = APSInt::getMinValue(Width, Unsigned);
889   APFloat MinSrc(SrcSema, APFloat::uninitialized);
890   if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
891       APFloat::opOverflow)
892     // Don't need an overflow check for lower bound. Just check for
893     // -Inf/NaN.
894     MinSrc = APFloat::getInf(SrcSema, true);
895   else
896     // Find the largest value which is too small to represent (before
897     // truncation toward zero).
898     MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
899 
900   APSInt Max = APSInt::getMaxValue(Width, Unsigned);
901   APFloat MaxSrc(SrcSema, APFloat::uninitialized);
902   if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
903       APFloat::opOverflow)
904     // Don't need an overflow check for upper bound. Just check for
905     // +Inf/NaN.
906     MaxSrc = APFloat::getInf(SrcSema, false);
907   else
908     // Find the smallest value which is too large to represent (before
909     // truncation toward zero).
910     MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
911 
912   // If we're converting from __half, convert the range to float to match
913   // the type of src.
914   if (OrigSrcType->isHalfType()) {
915     const llvm::fltSemantics &Sema =
916       CGF.getContext().getFloatTypeSemantics(SrcType);
917     bool IsInexact;
918     MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
919     MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
920   }
921 
922   llvm::Value *GE =
923     Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
924   llvm::Value *LE =
925     Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
926   Check = Builder.CreateAnd(GE, LE);
927 
928   llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
929                                   CGF.EmitCheckTypeDescriptor(OrigSrcType),
930                                   CGF.EmitCheckTypeDescriptor(DstType)};
931   CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
932                 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
933 }
934 
935 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
936 // Returns 'i1 false' when the truncation Src -> Dst was lossy.
937 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
938                  std::pair<llvm::Value *, SanitizerMask>>
939 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
940                                  QualType DstType, CGBuilderTy &Builder) {
941   llvm::Type *SrcTy = Src->getType();
942   llvm::Type *DstTy = Dst->getType();
943   (void)DstTy; // Only used in assert()
944 
945   // This should be truncation of integral types.
946   assert(Src != Dst);
947   assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
948   assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
949          "non-integer llvm type");
950 
951   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
952   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
953 
954   // If both (src and dst) types are unsigned, then it's an unsigned truncation.
955   // Else, it is a signed truncation.
956   ScalarExprEmitter::ImplicitConversionCheckKind Kind;
957   SanitizerMask Mask;
958   if (!SrcSigned && !DstSigned) {
959     Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
960     Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
961   } else {
962     Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
963     Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
964   }
965 
966   llvm::Value *Check = nullptr;
967   // 1. Extend the truncated value back to the same width as the Src.
968   Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
969   // 2. Equality-compare with the original source value
970   Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
971   // If the comparison result is 'i1 false', then the truncation was lossy.
972   return std::make_pair(Kind, std::make_pair(Check, Mask));
973 }
974 
975 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
976                                                    Value *Dst, QualType DstType,
977                                                    SourceLocation Loc) {
978   if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
979     return;
980 
981   // We only care about int->int conversions here.
982   // We ignore conversions to/from pointer and/or bool.
983   if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
984     return;
985 
986   unsigned SrcBits = Src->getType()->getScalarSizeInBits();
987   unsigned DstBits = Dst->getType()->getScalarSizeInBits();
988   // This must be truncation. Else we do not care.
989   if (SrcBits <= DstBits)
990     return;
991 
992   assert(!DstType->isBooleanType() && "we should not get here with booleans.");
993 
994   // If the integer sign change sanitizer is enabled,
995   // and we are truncating from larger unsigned type to smaller signed type,
996   // let that next sanitizer deal with it.
997   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
998   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
999   if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1000       (!SrcSigned && DstSigned))
1001     return;
1002 
1003   CodeGenFunction::SanitizerScope SanScope(&CGF);
1004 
1005   std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1006             std::pair<llvm::Value *, SanitizerMask>>
1007       Check =
1008           EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1009   // If the comparison result is 'i1 false', then the truncation was lossy.
1010 
1011   // Do we care about this type of truncation?
1012   if (!CGF.SanOpts.has(Check.second.second))
1013     return;
1014 
1015   llvm::Constant *StaticArgs[] = {
1016       CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1017       CGF.EmitCheckTypeDescriptor(DstType),
1018       llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1019   CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1020                 {Src, Dst});
1021 }
1022 
1023 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1024 // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1025 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1026                  std::pair<llvm::Value *, SanitizerMask>>
1027 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1028                                  QualType DstType, CGBuilderTy &Builder) {
1029   llvm::Type *SrcTy = Src->getType();
1030   llvm::Type *DstTy = Dst->getType();
1031 
1032   assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1033          "non-integer llvm type");
1034 
1035   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1036   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1037   (void)SrcSigned; // Only used in assert()
1038   (void)DstSigned; // Only used in assert()
1039   unsigned SrcBits = SrcTy->getScalarSizeInBits();
1040   unsigned DstBits = DstTy->getScalarSizeInBits();
1041   (void)SrcBits; // Only used in assert()
1042   (void)DstBits; // Only used in assert()
1043 
1044   assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1045          "either the widths should be different, or the signednesses.");
1046 
1047   // NOTE: zero value is considered to be non-negative.
1048   auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1049                                        const char *Name) -> Value * {
1050     // Is this value a signed type?
1051     bool VSigned = VType->isSignedIntegerOrEnumerationType();
1052     llvm::Type *VTy = V->getType();
1053     if (!VSigned) {
1054       // If the value is unsigned, then it is never negative.
1055       // FIXME: can we encounter non-scalar VTy here?
1056       return llvm::ConstantInt::getFalse(VTy->getContext());
1057     }
1058     // Get the zero of the same type with which we will be comparing.
1059     llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1060     // %V.isnegative = icmp slt %V, 0
1061     // I.e is %V *strictly* less than zero, does it have negative value?
1062     return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1063                               llvm::Twine(Name) + "." + V->getName() +
1064                                   ".negativitycheck");
1065   };
1066 
1067   // 1. Was the old Value negative?
1068   llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1069   // 2. Is the new Value negative?
1070   llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1071   // 3. Now, was the 'negativity status' preserved during the conversion?
1072   //    NOTE: conversion from negative to zero is considered to change the sign.
1073   //    (We want to get 'false' when the conversion changed the sign)
1074   //    So we should just equality-compare the negativity statuses.
1075   llvm::Value *Check = nullptr;
1076   Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1077   // If the comparison result is 'false', then the conversion changed the sign.
1078   return std::make_pair(
1079       ScalarExprEmitter::ICCK_IntegerSignChange,
1080       std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1081 }
1082 
1083 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1084                                                    Value *Dst, QualType DstType,
1085                                                    SourceLocation Loc) {
1086   if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1087     return;
1088 
1089   llvm::Type *SrcTy = Src->getType();
1090   llvm::Type *DstTy = Dst->getType();
1091 
1092   // We only care about int->int conversions here.
1093   // We ignore conversions to/from pointer and/or bool.
1094   if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
1095     return;
1096 
1097   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1098   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1099   unsigned SrcBits = SrcTy->getScalarSizeInBits();
1100   unsigned DstBits = DstTy->getScalarSizeInBits();
1101 
1102   // Now, we do not need to emit the check in *all* of the cases.
1103   // We can avoid emitting it in some obvious cases where it would have been
1104   // dropped by the opt passes (instcombine) always anyways.
1105   // If it's a cast between effectively the same type, no check.
1106   // NOTE: this is *not* equivalent to checking the canonical types.
1107   if (SrcSigned == DstSigned && SrcBits == DstBits)
1108     return;
1109   // At least one of the values needs to have signed type.
1110   // If both are unsigned, then obviously, neither of them can be negative.
1111   if (!SrcSigned && !DstSigned)
1112     return;
1113   // If the conversion is to *larger* *signed* type, then no check is needed.
1114   // Because either sign-extension happens (so the sign will remain),
1115   // or zero-extension will happen (the sign bit will be zero.)
1116   if ((DstBits > SrcBits) && DstSigned)
1117     return;
1118   if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1119       (SrcBits > DstBits) && SrcSigned) {
1120     // If the signed integer truncation sanitizer is enabled,
1121     // and this is a truncation from signed type, then no check is needed.
1122     // Because here sign change check is interchangeable with truncation check.
1123     return;
1124   }
1125   // That's it. We can't rule out any more cases with the data we have.
1126 
1127   CodeGenFunction::SanitizerScope SanScope(&CGF);
1128 
1129   std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1130             std::pair<llvm::Value *, SanitizerMask>>
1131       Check;
1132 
1133   // Each of these checks needs to return 'false' when an issue was detected.
1134   ImplicitConversionCheckKind CheckKind;
1135   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1136   // So we can 'and' all the checks together, and still get 'false',
1137   // if at least one of the checks detected an issue.
1138 
1139   Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1140   CheckKind = Check.first;
1141   Checks.emplace_back(Check.second);
1142 
1143   if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1144       (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1145     // If the signed integer truncation sanitizer was enabled,
1146     // and we are truncating from larger unsigned type to smaller signed type,
1147     // let's handle the case we skipped in that check.
1148     Check =
1149         EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1150     CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1151     Checks.emplace_back(Check.second);
1152     // If the comparison result is 'i1 false', then the truncation was lossy.
1153   }
1154 
1155   llvm::Constant *StaticArgs[] = {
1156       CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1157       CGF.EmitCheckTypeDescriptor(DstType),
1158       llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1159   // EmitCheck() will 'and' all the checks together.
1160   CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1161                 {Src, Dst});
1162 }
1163 
1164 /// Emit a conversion from the specified type to the specified destination type,
1165 /// both of which are LLVM scalar types.
1166 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1167                                                QualType DstType,
1168                                                SourceLocation Loc,
1169                                                ScalarConversionOpts Opts) {
1170   // All conversions involving fixed point types should be handled by the
1171   // EmitFixedPoint family functions. This is done to prevent bloating up this
1172   // function more, and although fixed point numbers are represented by
1173   // integers, we do not want to follow any logic that assumes they should be
1174   // treated as integers.
1175   // TODO(leonardchan): When necessary, add another if statement checking for
1176   // conversions to fixed point types from other types.
1177   if (SrcType->isFixedPointType()) {
1178     if (DstType->isBooleanType())
1179       // It is important that we check this before checking if the dest type is
1180       // an integer because booleans are technically integer types.
1181       // We do not need to check the padding bit on unsigned types if unsigned
1182       // padding is enabled because overflow into this bit is undefined
1183       // behavior.
1184       return Builder.CreateIsNotNull(Src, "tobool");
1185     if (DstType->isFixedPointType() || DstType->isIntegerType())
1186       return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1187 
1188     llvm_unreachable(
1189         "Unhandled scalar conversion from a fixed point type to another type.");
1190   } else if (DstType->isFixedPointType()) {
1191     if (SrcType->isIntegerType())
1192       // This also includes converting booleans and enums to fixed point types.
1193       return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1194 
1195     llvm_unreachable(
1196         "Unhandled scalar conversion to a fixed point type from another type.");
1197   }
1198 
1199   QualType NoncanonicalSrcType = SrcType;
1200   QualType NoncanonicalDstType = DstType;
1201 
1202   SrcType = CGF.getContext().getCanonicalType(SrcType);
1203   DstType = CGF.getContext().getCanonicalType(DstType);
1204   if (SrcType == DstType) return Src;
1205 
1206   if (DstType->isVoidType()) return nullptr;
1207 
1208   llvm::Value *OrigSrc = Src;
1209   QualType OrigSrcType = SrcType;
1210   llvm::Type *SrcTy = Src->getType();
1211 
1212   // Handle conversions to bool first, they are special: comparisons against 0.
1213   if (DstType->isBooleanType())
1214     return EmitConversionToBool(Src, SrcType);
1215 
1216   llvm::Type *DstTy = ConvertType(DstType);
1217 
1218   // Cast from half through float if half isn't a native type.
1219   if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1220     // Cast to FP using the intrinsic if the half type itself isn't supported.
1221     if (DstTy->isFloatingPointTy()) {
1222       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1223         return Builder.CreateCall(
1224             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1225             Src);
1226     } else {
1227       // Cast to other types through float, using either the intrinsic or FPExt,
1228       // depending on whether the half type itself is supported
1229       // (as opposed to operations on half, available with NativeHalfType).
1230       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1231         Src = Builder.CreateCall(
1232             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1233                                  CGF.CGM.FloatTy),
1234             Src);
1235       } else {
1236         Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1237       }
1238       SrcType = CGF.getContext().FloatTy;
1239       SrcTy = CGF.FloatTy;
1240     }
1241   }
1242 
1243   // Ignore conversions like int -> uint.
1244   if (SrcTy == DstTy) {
1245     if (Opts.EmitImplicitIntegerSignChangeChecks)
1246       EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1247                                  NoncanonicalDstType, Loc);
1248 
1249     return Src;
1250   }
1251 
1252   // Handle pointer conversions next: pointers can only be converted to/from
1253   // other pointers and integers. Check for pointer types in terms of LLVM, as
1254   // some native types (like Obj-C id) may map to a pointer type.
1255   if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1256     // The source value may be an integer, or a pointer.
1257     if (isa<llvm::PointerType>(SrcTy))
1258       return Builder.CreateBitCast(Src, DstTy, "conv");
1259 
1260     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1261     // First, convert to the correct width so that we control the kind of
1262     // extension.
1263     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1264     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1265     llvm::Value* IntResult =
1266         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1267     // Then, cast to pointer.
1268     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
1269   }
1270 
1271   if (isa<llvm::PointerType>(SrcTy)) {
1272     // Must be an ptr to int cast.
1273     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1274     return Builder.CreatePtrToInt(Src, DstTy, "conv");
1275   }
1276 
1277   // A scalar can be splatted to an extended vector of the same element type
1278   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1279     // Sema should add casts to make sure that the source expression's type is
1280     // the same as the vector's element type (sans qualifiers)
1281     assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1282                SrcType.getTypePtr() &&
1283            "Splatted expr doesn't match with vector element type?");
1284 
1285     // Splat the element across to all elements
1286     unsigned NumElements = DstTy->getVectorNumElements();
1287     return Builder.CreateVectorSplat(NumElements, Src, "splat");
1288   }
1289 
1290   if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1291     // Allow bitcast from vector to integer/fp of the same size.
1292     unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1293     unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1294     if (SrcSize == DstSize)
1295       return Builder.CreateBitCast(Src, DstTy, "conv");
1296 
1297     // Conversions between vectors of different sizes are not allowed except
1298     // when vectors of half are involved. Operations on storage-only half
1299     // vectors require promoting half vector operands to float vectors and
1300     // truncating the result, which is either an int or float vector, to a
1301     // short or half vector.
1302 
1303     // Source and destination are both expected to be vectors.
1304     llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
1305     llvm::Type *DstElementTy = DstTy->getVectorElementType();
1306     (void)DstElementTy;
1307 
1308     assert(((SrcElementTy->isIntegerTy() &&
1309              DstElementTy->isIntegerTy()) ||
1310             (SrcElementTy->isFloatingPointTy() &&
1311              DstElementTy->isFloatingPointTy())) &&
1312            "unexpected conversion between a floating-point vector and an "
1313            "integer vector");
1314 
1315     // Truncate an i32 vector to an i16 vector.
1316     if (SrcElementTy->isIntegerTy())
1317       return Builder.CreateIntCast(Src, DstTy, false, "conv");
1318 
1319     // Truncate a float vector to a half vector.
1320     if (SrcSize > DstSize)
1321       return Builder.CreateFPTrunc(Src, DstTy, "conv");
1322 
1323     // Promote a half vector to a float vector.
1324     return Builder.CreateFPExt(Src, DstTy, "conv");
1325   }
1326 
1327   // Finally, we have the arithmetic types: real int/float.
1328   Value *Res = nullptr;
1329   llvm::Type *ResTy = DstTy;
1330 
1331   // An overflowing conversion has undefined behavior if either the source type
1332   // or the destination type is a floating-point type. However, we consider the
1333   // range of representable values for all floating-point types to be
1334   // [-inf,+inf], so no overflow can ever happen when the destination type is a
1335   // floating-point type.
1336   if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
1337       OrigSrcType->isFloatingType())
1338     EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1339                              Loc);
1340 
1341   // Cast to half through float if half isn't a native type.
1342   if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1343     // Make sure we cast in a single step if from another FP type.
1344     if (SrcTy->isFloatingPointTy()) {
1345       // Use the intrinsic if the half type itself isn't supported
1346       // (as opposed to operations on half, available with NativeHalfType).
1347       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1348         return Builder.CreateCall(
1349             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1350       // If the half type is supported, just use an fptrunc.
1351       return Builder.CreateFPTrunc(Src, DstTy);
1352     }
1353     DstTy = CGF.FloatTy;
1354   }
1355 
1356   if (isa<llvm::IntegerType>(SrcTy)) {
1357     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1358     if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1359       InputSigned = true;
1360     }
1361     if (isa<llvm::IntegerType>(DstTy))
1362       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1363     else if (InputSigned)
1364       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1365     else
1366       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1367   } else if (isa<llvm::IntegerType>(DstTy)) {
1368     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
1369     if (DstType->isSignedIntegerOrEnumerationType())
1370       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1371     else
1372       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1373   } else {
1374     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1375            "Unknown real conversion");
1376     if (DstTy->getTypeID() < SrcTy->getTypeID())
1377       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1378     else
1379       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1380   }
1381 
1382   if (DstTy != ResTy) {
1383     if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1384       assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1385       Res = Builder.CreateCall(
1386         CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1387         Res);
1388     } else {
1389       Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1390     }
1391   }
1392 
1393   if (Opts.EmitImplicitIntegerTruncationChecks)
1394     EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1395                                NoncanonicalDstType, Loc);
1396 
1397   if (Opts.EmitImplicitIntegerSignChangeChecks)
1398     EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1399                                NoncanonicalDstType, Loc);
1400 
1401   return Res;
1402 }
1403 
1404 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1405                                                    QualType DstTy,
1406                                                    SourceLocation Loc) {
1407   FixedPointSemantics SrcFPSema =
1408       CGF.getContext().getFixedPointSemantics(SrcTy);
1409   FixedPointSemantics DstFPSema =
1410       CGF.getContext().getFixedPointSemantics(DstTy);
1411   return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc,
1412                                   DstTy->isIntegerType());
1413 }
1414 
1415 Value *ScalarExprEmitter::EmitFixedPointConversion(
1416     Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
1417     SourceLocation Loc, bool DstIsInteger) {
1418   using llvm::APInt;
1419   using llvm::ConstantInt;
1420   using llvm::Value;
1421 
1422   unsigned SrcWidth = SrcFPSema.getWidth();
1423   unsigned DstWidth = DstFPSema.getWidth();
1424   unsigned SrcScale = SrcFPSema.getScale();
1425   unsigned DstScale = DstFPSema.getScale();
1426   bool SrcIsSigned = SrcFPSema.isSigned();
1427   bool DstIsSigned = DstFPSema.isSigned();
1428 
1429   llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
1430 
1431   Value *Result = Src;
1432   unsigned ResultWidth = SrcWidth;
1433 
1434   // Downscale.
1435   if (DstScale < SrcScale) {
1436     // When converting to integers, we round towards zero. For negative numbers,
1437     // right shifting rounds towards negative infinity. In this case, we can
1438     // just round up before shifting.
1439     if (DstIsInteger && SrcIsSigned) {
1440       Value *Zero = llvm::Constant::getNullValue(Result->getType());
1441       Value *IsNegative = Builder.CreateICmpSLT(Result, Zero);
1442       Value *LowBits = ConstantInt::get(
1443           CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
1444       Value *Rounded = Builder.CreateAdd(Result, LowBits);
1445       Result = Builder.CreateSelect(IsNegative, Rounded, Result);
1446     }
1447 
1448     Result = SrcIsSigned
1449                  ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale")
1450                  : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
1451   }
1452 
1453   if (!DstFPSema.isSaturated()) {
1454     // Resize.
1455     Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
1456 
1457     // Upscale.
1458     if (DstScale > SrcScale)
1459       Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
1460   } else {
1461     // Adjust the number of fractional bits.
1462     if (DstScale > SrcScale) {
1463       // Compare to DstWidth to prevent resizing twice.
1464       ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
1465       llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
1466       Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
1467       Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
1468     }
1469 
1470     // Handle saturation.
1471     bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
1472     if (LessIntBits) {
1473       Value *Max = ConstantInt::get(
1474           CGF.getLLVMContext(),
1475           APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
1476       Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
1477                                    : Builder.CreateICmpUGT(Result, Max);
1478       Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
1479     }
1480     // Cannot overflow min to dest type if src is unsigned since all fixed
1481     // point types can cover the unsigned min of 0.
1482     if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
1483       Value *Min = ConstantInt::get(
1484           CGF.getLLVMContext(),
1485           APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
1486       Value *TooLow = Builder.CreateICmpSLT(Result, Min);
1487       Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
1488     }
1489 
1490     // Resize the integer part to get the final destination size.
1491     if (ResultWidth != DstWidth)
1492       Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
1493   }
1494   return Result;
1495 }
1496 
1497 /// Emit a conversion from the specified complex type to the specified
1498 /// destination type, where the destination type is an LLVM scalar type.
1499 Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1500     CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1501     SourceLocation Loc) {
1502   // Get the source element type.
1503   SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1504 
1505   // Handle conversions to bool first, they are special: comparisons against 0.
1506   if (DstTy->isBooleanType()) {
1507     //  Complex != 0  -> (Real != 0) | (Imag != 0)
1508     Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1509     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1510     return Builder.CreateOr(Src.first, Src.second, "tobool");
1511   }
1512 
1513   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1514   // the imaginary part of the complex value is discarded and the value of the
1515   // real part is converted according to the conversion rules for the
1516   // corresponding real type.
1517   return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1518 }
1519 
1520 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1521   return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1522 }
1523 
1524 /// Emit a sanitization check for the given "binary" operation (which
1525 /// might actually be a unary increment which has been lowered to a binary
1526 /// operation). The check passes if all values in \p Checks (which are \c i1),
1527 /// are \c true.
1528 void ScalarExprEmitter::EmitBinOpCheck(
1529     ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1530   assert(CGF.IsSanitizerScope);
1531   SanitizerHandler Check;
1532   SmallVector<llvm::Constant *, 4> StaticData;
1533   SmallVector<llvm::Value *, 2> DynamicData;
1534 
1535   BinaryOperatorKind Opcode = Info.Opcode;
1536   if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1537     Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1538 
1539   StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1540   const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1541   if (UO && UO->getOpcode() == UO_Minus) {
1542     Check = SanitizerHandler::NegateOverflow;
1543     StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1544     DynamicData.push_back(Info.RHS);
1545   } else {
1546     if (BinaryOperator::isShiftOp(Opcode)) {
1547       // Shift LHS negative or too large, or RHS out of bounds.
1548       Check = SanitizerHandler::ShiftOutOfBounds;
1549       const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1550       StaticData.push_back(
1551         CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1552       StaticData.push_back(
1553         CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1554     } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1555       // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1556       Check = SanitizerHandler::DivremOverflow;
1557       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1558     } else {
1559       // Arithmetic overflow (+, -, *).
1560       switch (Opcode) {
1561       case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1562       case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1563       case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1564       default: llvm_unreachable("unexpected opcode for bin op check");
1565       }
1566       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1567     }
1568     DynamicData.push_back(Info.LHS);
1569     DynamicData.push_back(Info.RHS);
1570   }
1571 
1572   CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1573 }
1574 
1575 //===----------------------------------------------------------------------===//
1576 //                            Visitor Methods
1577 //===----------------------------------------------------------------------===//
1578 
1579 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1580   CGF.ErrorUnsupported(E, "scalar expression");
1581   if (E->getType()->isVoidType())
1582     return nullptr;
1583   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1584 }
1585 
1586 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1587   // Vector Mask Case
1588   if (E->getNumSubExprs() == 2) {
1589     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1590     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1591     Value *Mask;
1592 
1593     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
1594     unsigned LHSElts = LTy->getNumElements();
1595 
1596     Mask = RHS;
1597 
1598     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
1599 
1600     // Mask off the high bits of each shuffle index.
1601     Value *MaskBits =
1602         llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1603     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1604 
1605     // newv = undef
1606     // mask = mask & maskbits
1607     // for each elt
1608     //   n = extract mask i
1609     //   x = extract val n
1610     //   newv = insert newv, x, i
1611     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
1612                                                   MTy->getNumElements());
1613     Value* NewV = llvm::UndefValue::get(RTy);
1614     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
1615       Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1616       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1617 
1618       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1619       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1620     }
1621     return NewV;
1622   }
1623 
1624   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1625   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1626 
1627   SmallVector<llvm::Constant*, 32> indices;
1628   for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1629     llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1630     // Check for -1 and output it as undef in the IR.
1631     if (Idx.isSigned() && Idx.isAllOnesValue())
1632       indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1633     else
1634       indices.push_back(Builder.getInt32(Idx.getZExtValue()));
1635   }
1636 
1637   Value *SV = llvm::ConstantVector::get(indices);
1638   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1639 }
1640 
1641 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1642   QualType SrcType = E->getSrcExpr()->getType(),
1643            DstType = E->getType();
1644 
1645   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
1646 
1647   SrcType = CGF.getContext().getCanonicalType(SrcType);
1648   DstType = CGF.getContext().getCanonicalType(DstType);
1649   if (SrcType == DstType) return Src;
1650 
1651   assert(SrcType->isVectorType() &&
1652          "ConvertVector source type must be a vector");
1653   assert(DstType->isVectorType() &&
1654          "ConvertVector destination type must be a vector");
1655 
1656   llvm::Type *SrcTy = Src->getType();
1657   llvm::Type *DstTy = ConvertType(DstType);
1658 
1659   // Ignore conversions like int -> uint.
1660   if (SrcTy == DstTy)
1661     return Src;
1662 
1663   QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1664            DstEltType = DstType->castAs<VectorType>()->getElementType();
1665 
1666   assert(SrcTy->isVectorTy() &&
1667          "ConvertVector source IR type must be a vector");
1668   assert(DstTy->isVectorTy() &&
1669          "ConvertVector destination IR type must be a vector");
1670 
1671   llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1672              *DstEltTy = DstTy->getVectorElementType();
1673 
1674   if (DstEltType->isBooleanType()) {
1675     assert((SrcEltTy->isFloatingPointTy() ||
1676             isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1677 
1678     llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1679     if (SrcEltTy->isFloatingPointTy()) {
1680       return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1681     } else {
1682       return Builder.CreateICmpNE(Src, Zero, "tobool");
1683     }
1684   }
1685 
1686   // We have the arithmetic types: real int/float.
1687   Value *Res = nullptr;
1688 
1689   if (isa<llvm::IntegerType>(SrcEltTy)) {
1690     bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1691     if (isa<llvm::IntegerType>(DstEltTy))
1692       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1693     else if (InputSigned)
1694       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1695     else
1696       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1697   } else if (isa<llvm::IntegerType>(DstEltTy)) {
1698     assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1699     if (DstEltType->isSignedIntegerOrEnumerationType())
1700       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1701     else
1702       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1703   } else {
1704     assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1705            "Unknown real conversion");
1706     if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1707       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1708     else
1709       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1710   }
1711 
1712   return Res;
1713 }
1714 
1715 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1716   if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1717     CGF.EmitIgnoredExpr(E->getBase());
1718     return CGF.emitScalarConstant(Constant, E);
1719   } else {
1720     Expr::EvalResult Result;
1721     if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1722       llvm::APSInt Value = Result.Val.getInt();
1723       CGF.EmitIgnoredExpr(E->getBase());
1724       return Builder.getInt(Value);
1725     }
1726   }
1727 
1728   return EmitLoadOfLValue(E);
1729 }
1730 
1731 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1732   TestAndClearIgnoreResultAssign();
1733 
1734   // Emit subscript expressions in rvalue context's.  For most cases, this just
1735   // loads the lvalue formed by the subscript expr.  However, we have to be
1736   // careful, because the base of a vector subscript is occasionally an rvalue,
1737   // so we can't get it as an lvalue.
1738   if (!E->getBase()->getType()->isVectorType())
1739     return EmitLoadOfLValue(E);
1740 
1741   // Handle the vector case.  The base must be a vector, the index must be an
1742   // integer value.
1743   Value *Base = Visit(E->getBase());
1744   Value *Idx  = Visit(E->getIdx());
1745   QualType IdxTy = E->getIdx()->getType();
1746 
1747   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1748     CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1749 
1750   return Builder.CreateExtractElement(Base, Idx, "vecext");
1751 }
1752 
1753 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1754                                   unsigned Off, llvm::Type *I32Ty) {
1755   int MV = SVI->getMaskValue(Idx);
1756   if (MV == -1)
1757     return llvm::UndefValue::get(I32Ty);
1758   return llvm::ConstantInt::get(I32Ty, Off+MV);
1759 }
1760 
1761 static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1762   if (C->getBitWidth() != 32) {
1763       assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1764                                                     C->getZExtValue()) &&
1765              "Index operand too large for shufflevector mask!");
1766       return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1767   }
1768   return C;
1769 }
1770 
1771 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1772   bool Ignore = TestAndClearIgnoreResultAssign();
1773   (void)Ignore;
1774   assert (Ignore == false && "init list ignored");
1775   unsigned NumInitElements = E->getNumInits();
1776 
1777   if (E->hadArrayRangeDesignator())
1778     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1779 
1780   llvm::VectorType *VType =
1781     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1782 
1783   if (!VType) {
1784     if (NumInitElements == 0) {
1785       // C++11 value-initialization for the scalar.
1786       return EmitNullValue(E->getType());
1787     }
1788     // We have a scalar in braces. Just use the first element.
1789     return Visit(E->getInit(0));
1790   }
1791 
1792   unsigned ResElts = VType->getNumElements();
1793 
1794   // Loop over initializers collecting the Value for each, and remembering
1795   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
1796   // us to fold the shuffle for the swizzle into the shuffle for the vector
1797   // initializer, since LLVM optimizers generally do not want to touch
1798   // shuffles.
1799   unsigned CurIdx = 0;
1800   bool VIsUndefShuffle = false;
1801   llvm::Value *V = llvm::UndefValue::get(VType);
1802   for (unsigned i = 0; i != NumInitElements; ++i) {
1803     Expr *IE = E->getInit(i);
1804     Value *Init = Visit(IE);
1805     SmallVector<llvm::Constant*, 16> Args;
1806 
1807     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1808 
1809     // Handle scalar elements.  If the scalar initializer is actually one
1810     // element of a different vector of the same width, use shuffle instead of
1811     // extract+insert.
1812     if (!VVT) {
1813       if (isa<ExtVectorElementExpr>(IE)) {
1814         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1815 
1816         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1817           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1818           Value *LHS = nullptr, *RHS = nullptr;
1819           if (CurIdx == 0) {
1820             // insert into undef -> shuffle (src, undef)
1821             // shufflemask must use an i32
1822             Args.push_back(getAsInt32(C, CGF.Int32Ty));
1823             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1824 
1825             LHS = EI->getVectorOperand();
1826             RHS = V;
1827             VIsUndefShuffle = true;
1828           } else if (VIsUndefShuffle) {
1829             // insert into undefshuffle && size match -> shuffle (v, src)
1830             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1831             for (unsigned j = 0; j != CurIdx; ++j)
1832               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1833             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1834             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1835 
1836             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1837             RHS = EI->getVectorOperand();
1838             VIsUndefShuffle = false;
1839           }
1840           if (!Args.empty()) {
1841             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1842             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1843             ++CurIdx;
1844             continue;
1845           }
1846         }
1847       }
1848       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1849                                       "vecinit");
1850       VIsUndefShuffle = false;
1851       ++CurIdx;
1852       continue;
1853     }
1854 
1855     unsigned InitElts = VVT->getNumElements();
1856 
1857     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1858     // input is the same width as the vector being constructed, generate an
1859     // optimized shuffle of the swizzle input into the result.
1860     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1861     if (isa<ExtVectorElementExpr>(IE)) {
1862       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1863       Value *SVOp = SVI->getOperand(0);
1864       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1865 
1866       if (OpTy->getNumElements() == ResElts) {
1867         for (unsigned j = 0; j != CurIdx; ++j) {
1868           // If the current vector initializer is a shuffle with undef, merge
1869           // this shuffle directly into it.
1870           if (VIsUndefShuffle) {
1871             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1872                                       CGF.Int32Ty));
1873           } else {
1874             Args.push_back(Builder.getInt32(j));
1875           }
1876         }
1877         for (unsigned j = 0, je = InitElts; j != je; ++j)
1878           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1879         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1880 
1881         if (VIsUndefShuffle)
1882           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1883 
1884         Init = SVOp;
1885       }
1886     }
1887 
1888     // Extend init to result vector length, and then shuffle its contribution
1889     // to the vector initializer into V.
1890     if (Args.empty()) {
1891       for (unsigned j = 0; j != InitElts; ++j)
1892         Args.push_back(Builder.getInt32(j));
1893       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1894       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1895       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1896                                          Mask, "vext");
1897 
1898       Args.clear();
1899       for (unsigned j = 0; j != CurIdx; ++j)
1900         Args.push_back(Builder.getInt32(j));
1901       for (unsigned j = 0; j != InitElts; ++j)
1902         Args.push_back(Builder.getInt32(j+Offset));
1903       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1904     }
1905 
1906     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1907     // merging subsequent shuffles into this one.
1908     if (CurIdx == 0)
1909       std::swap(V, Init);
1910     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1911     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1912     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1913     CurIdx += InitElts;
1914   }
1915 
1916   // FIXME: evaluate codegen vs. shuffling against constant null vector.
1917   // Emit remaining default initializers.
1918   llvm::Type *EltTy = VType->getElementType();
1919 
1920   // Emit remaining default initializers
1921   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1922     Value *Idx = Builder.getInt32(CurIdx);
1923     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1924     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1925   }
1926   return V;
1927 }
1928 
1929 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
1930   const Expr *E = CE->getSubExpr();
1931 
1932   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1933     return false;
1934 
1935   if (isa<CXXThisExpr>(E->IgnoreParens())) {
1936     // We always assume that 'this' is never null.
1937     return false;
1938   }
1939 
1940   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1941     // And that glvalue casts are never null.
1942     if (ICE->getValueKind() != VK_RValue)
1943       return false;
1944   }
1945 
1946   return true;
1947 }
1948 
1949 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1950 // have to handle a more broad range of conversions than explicit casts, as they
1951 // handle things like function to ptr-to-function decay etc.
1952 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1953   Expr *E = CE->getSubExpr();
1954   QualType DestTy = CE->getType();
1955   CastKind Kind = CE->getCastKind();
1956 
1957   // These cases are generally not written to ignore the result of
1958   // evaluating their sub-expressions, so we clear this now.
1959   bool Ignored = TestAndClearIgnoreResultAssign();
1960 
1961   // Since almost all cast kinds apply to scalars, this switch doesn't have
1962   // a default case, so the compiler will warn on a missing case.  The cases
1963   // are in the same order as in the CastKind enum.
1964   switch (Kind) {
1965   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1966   case CK_BuiltinFnToFnPtr:
1967     llvm_unreachable("builtin functions are handled elsewhere");
1968 
1969   case CK_LValueBitCast:
1970   case CK_ObjCObjectLValueCast: {
1971     Address Addr = EmitLValue(E).getAddress();
1972     Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
1973     LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1974     return EmitLoadOfLValue(LV, CE->getExprLoc());
1975   }
1976 
1977   case CK_LValueToRValueBitCast: {
1978     LValue SourceLVal = CGF.EmitLValue(E);
1979     Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(),
1980                                                 CGF.ConvertTypeForMem(DestTy));
1981     LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
1982     DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
1983     return EmitLoadOfLValue(DestLV, CE->getExprLoc());
1984   }
1985 
1986   case CK_CPointerToObjCPointerCast:
1987   case CK_BlockPointerToObjCPointerCast:
1988   case CK_AnyPointerToBlockPointerCast:
1989   case CK_BitCast: {
1990     Value *Src = Visit(const_cast<Expr*>(E));
1991     llvm::Type *SrcTy = Src->getType();
1992     llvm::Type *DstTy = ConvertType(DestTy);
1993     if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
1994         SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
1995       llvm_unreachable("wrong cast for pointers in different address spaces"
1996                        "(must be an address space cast)!");
1997     }
1998 
1999     if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2000       if (auto PT = DestTy->getAs<PointerType>())
2001         CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
2002                                       /*MayBeNull=*/true,
2003                                       CodeGenFunction::CFITCK_UnrelatedCast,
2004                                       CE->getBeginLoc());
2005     }
2006 
2007     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2008       const QualType SrcType = E->getType();
2009 
2010       if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2011         // Casting to pointer that could carry dynamic information (provided by
2012         // invariant.group) requires launder.
2013         Src = Builder.CreateLaunderInvariantGroup(Src);
2014       } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2015         // Casting to pointer that does not carry dynamic information (provided
2016         // by invariant.group) requires stripping it.  Note that we don't do it
2017         // if the source could not be dynamic type and destination could be
2018         // dynamic because dynamic information is already laundered.  It is
2019         // because launder(strip(src)) == launder(src), so there is no need to
2020         // add extra strip before launder.
2021         Src = Builder.CreateStripInvariantGroup(Src);
2022       }
2023     }
2024 
2025     // Update heapallocsite metadata when there is an explicit cast.
2026     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src))
2027       if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE))
2028           CGF.getDebugInfo()->
2029               addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
2030 
2031     return Builder.CreateBitCast(Src, DstTy);
2032   }
2033   case CK_AddressSpaceConversion: {
2034     Expr::EvalResult Result;
2035     if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2036         Result.Val.isNullPointer()) {
2037       // If E has side effect, it is emitted even if its final result is a
2038       // null pointer. In that case, a DCE pass should be able to
2039       // eliminate the useless instructions emitted during translating E.
2040       if (Result.HasSideEffects)
2041         Visit(E);
2042       return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2043           ConvertType(DestTy)), DestTy);
2044     }
2045     // Since target may map different address spaces in AST to the same address
2046     // space, an address space conversion may end up as a bitcast.
2047     return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2048         CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2049         DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2050   }
2051   case CK_AtomicToNonAtomic:
2052   case CK_NonAtomicToAtomic:
2053   case CK_NoOp:
2054   case CK_UserDefinedConversion:
2055     return Visit(const_cast<Expr*>(E));
2056 
2057   case CK_BaseToDerived: {
2058     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2059     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2060 
2061     Address Base = CGF.EmitPointerWithAlignment(E);
2062     Address Derived =
2063       CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2064                                    CE->path_begin(), CE->path_end(),
2065                                    CGF.ShouldNullCheckClassCastValue(CE));
2066 
2067     // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2068     // performed and the object is not of the derived type.
2069     if (CGF.sanitizePerformTypeCheck())
2070       CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2071                         Derived.getPointer(), DestTy->getPointeeType());
2072 
2073     if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2074       CGF.EmitVTablePtrCheckForCast(
2075           DestTy->getPointeeType(), Derived.getPointer(),
2076           /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2077           CE->getBeginLoc());
2078 
2079     return Derived.getPointer();
2080   }
2081   case CK_UncheckedDerivedToBase:
2082   case CK_DerivedToBase: {
2083     // The EmitPointerWithAlignment path does this fine; just discard
2084     // the alignment.
2085     return CGF.EmitPointerWithAlignment(CE).getPointer();
2086   }
2087 
2088   case CK_Dynamic: {
2089     Address V = CGF.EmitPointerWithAlignment(E);
2090     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2091     return CGF.EmitDynamicCast(V, DCE);
2092   }
2093 
2094   case CK_ArrayToPointerDecay:
2095     return CGF.EmitArrayToPointerDecay(E).getPointer();
2096   case CK_FunctionToPointerDecay:
2097     return EmitLValue(E).getPointer();
2098 
2099   case CK_NullToPointer:
2100     if (MustVisitNullValue(E))
2101       CGF.EmitIgnoredExpr(E);
2102 
2103     return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2104                               DestTy);
2105 
2106   case CK_NullToMemberPointer: {
2107     if (MustVisitNullValue(E))
2108       CGF.EmitIgnoredExpr(E);
2109 
2110     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2111     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2112   }
2113 
2114   case CK_ReinterpretMemberPointer:
2115   case CK_BaseToDerivedMemberPointer:
2116   case CK_DerivedToBaseMemberPointer: {
2117     Value *Src = Visit(E);
2118 
2119     // Note that the AST doesn't distinguish between checked and
2120     // unchecked member pointer conversions, so we always have to
2121     // implement checked conversions here.  This is inefficient when
2122     // actual control flow may be required in order to perform the
2123     // check, which it is for data member pointers (but not member
2124     // function pointers on Itanium and ARM).
2125     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2126   }
2127 
2128   case CK_ARCProduceObject:
2129     return CGF.EmitARCRetainScalarExpr(E);
2130   case CK_ARCConsumeObject:
2131     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2132   case CK_ARCReclaimReturnedObject:
2133     return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2134   case CK_ARCExtendBlockObject:
2135     return CGF.EmitARCExtendBlockObject(E);
2136 
2137   case CK_CopyAndAutoreleaseBlockObject:
2138     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2139 
2140   case CK_FloatingRealToComplex:
2141   case CK_FloatingComplexCast:
2142   case CK_IntegralRealToComplex:
2143   case CK_IntegralComplexCast:
2144   case CK_IntegralComplexToFloatingComplex:
2145   case CK_FloatingComplexToIntegralComplex:
2146   case CK_ConstructorConversion:
2147   case CK_ToUnion:
2148     llvm_unreachable("scalar cast to non-scalar value");
2149 
2150   case CK_LValueToRValue:
2151     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2152     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2153     return Visit(const_cast<Expr*>(E));
2154 
2155   case CK_IntegralToPointer: {
2156     Value *Src = Visit(const_cast<Expr*>(E));
2157 
2158     // First, convert to the correct width so that we control the kind of
2159     // extension.
2160     auto DestLLVMTy = ConvertType(DestTy);
2161     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2162     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2163     llvm::Value* IntResult =
2164       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2165 
2166     auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2167 
2168     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2169       // Going from integer to pointer that could be dynamic requires reloading
2170       // dynamic information from invariant.group.
2171       if (DestTy.mayBeDynamicClass())
2172         IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2173     }
2174     return IntToPtr;
2175   }
2176   case CK_PointerToIntegral: {
2177     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2178     auto *PtrExpr = Visit(E);
2179 
2180     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2181       const QualType SrcType = E->getType();
2182 
2183       // Casting to integer requires stripping dynamic information as it does
2184       // not carries it.
2185       if (SrcType.mayBeDynamicClass())
2186         PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2187     }
2188 
2189     return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2190   }
2191   case CK_ToVoid: {
2192     CGF.EmitIgnoredExpr(E);
2193     return nullptr;
2194   }
2195   case CK_VectorSplat: {
2196     llvm::Type *DstTy = ConvertType(DestTy);
2197     Value *Elt = Visit(const_cast<Expr*>(E));
2198     // Splat the element across to all elements
2199     unsigned NumElements = DstTy->getVectorNumElements();
2200     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2201   }
2202 
2203   case CK_FixedPointCast:
2204     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2205                                 CE->getExprLoc());
2206 
2207   case CK_FixedPointToBoolean:
2208     assert(E->getType()->isFixedPointType() &&
2209            "Expected src type to be fixed point type");
2210     assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2211     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2212                                 CE->getExprLoc());
2213 
2214   case CK_FixedPointToIntegral:
2215     assert(E->getType()->isFixedPointType() &&
2216            "Expected src type to be fixed point type");
2217     assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2218     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2219                                 CE->getExprLoc());
2220 
2221   case CK_IntegralToFixedPoint:
2222     assert(E->getType()->isIntegerType() &&
2223            "Expected src type to be an integer");
2224     assert(DestTy->isFixedPointType() &&
2225            "Expected dest type to be fixed point type");
2226     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2227                                 CE->getExprLoc());
2228 
2229   case CK_IntegralCast: {
2230     ScalarConversionOpts Opts;
2231     if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2232       if (!ICE->isPartOfExplicitCast())
2233         Opts = ScalarConversionOpts(CGF.SanOpts);
2234     }
2235     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2236                                 CE->getExprLoc(), Opts);
2237   }
2238   case CK_IntegralToFloating:
2239   case CK_FloatingToIntegral:
2240   case CK_FloatingCast:
2241     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2242                                 CE->getExprLoc());
2243   case CK_BooleanToSignedIntegral: {
2244     ScalarConversionOpts Opts;
2245     Opts.TreatBooleanAsSigned = true;
2246     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2247                                 CE->getExprLoc(), Opts);
2248   }
2249   case CK_IntegralToBoolean:
2250     return EmitIntToBoolConversion(Visit(E));
2251   case CK_PointerToBoolean:
2252     return EmitPointerToBoolConversion(Visit(E), E->getType());
2253   case CK_FloatingToBoolean:
2254     return EmitFloatToBoolConversion(Visit(E));
2255   case CK_MemberPointerToBoolean: {
2256     llvm::Value *MemPtr = Visit(E);
2257     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2258     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2259   }
2260 
2261   case CK_FloatingComplexToReal:
2262   case CK_IntegralComplexToReal:
2263     return CGF.EmitComplexExpr(E, false, true).first;
2264 
2265   case CK_FloatingComplexToBoolean:
2266   case CK_IntegralComplexToBoolean: {
2267     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2268 
2269     // TODO: kill this function off, inline appropriate case here
2270     return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2271                                          CE->getExprLoc());
2272   }
2273 
2274   case CK_ZeroToOCLOpaqueType: {
2275     assert((DestTy->isEventT() || DestTy->isQueueT() ||
2276             DestTy->isOCLIntelSubgroupAVCType()) &&
2277            "CK_ZeroToOCLEvent cast on non-event type");
2278     return llvm::Constant::getNullValue(ConvertType(DestTy));
2279   }
2280 
2281   case CK_IntToOCLSampler:
2282     return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2283 
2284   } // end of switch
2285 
2286   llvm_unreachable("unknown scalar cast");
2287 }
2288 
2289 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2290   CodeGenFunction::StmtExprEvaluation eval(CGF);
2291   Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2292                                            !E->getType()->isVoidType());
2293   if (!RetAlloca.isValid())
2294     return nullptr;
2295   return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2296                               E->getExprLoc());
2297 }
2298 
2299 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2300   CGF.enterFullExpression(E);
2301   CodeGenFunction::RunCleanupsScope Scope(CGF);
2302   Value *V = Visit(E->getSubExpr());
2303   // Defend against dominance problems caused by jumps out of expression
2304   // evaluation through the shared cleanup block.
2305   Scope.ForceCleanup({&V});
2306   return V;
2307 }
2308 
2309 //===----------------------------------------------------------------------===//
2310 //                             Unary Operators
2311 //===----------------------------------------------------------------------===//
2312 
2313 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2314                                            llvm::Value *InVal, bool IsInc) {
2315   BinOpInfo BinOp;
2316   BinOp.LHS = InVal;
2317   BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2318   BinOp.Ty = E->getType();
2319   BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
2320   // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2321   BinOp.E = E;
2322   return BinOp;
2323 }
2324 
2325 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2326     const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2327   llvm::Value *Amount =
2328       llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2329   StringRef Name = IsInc ? "inc" : "dec";
2330   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2331   case LangOptions::SOB_Defined:
2332     return Builder.CreateAdd(InVal, Amount, Name);
2333   case LangOptions::SOB_Undefined:
2334     if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2335       return Builder.CreateNSWAdd(InVal, Amount, Name);
2336     LLVM_FALLTHROUGH;
2337   case LangOptions::SOB_Trapping:
2338     if (!E->canOverflow())
2339       return Builder.CreateNSWAdd(InVal, Amount, Name);
2340     return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
2341   }
2342   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2343 }
2344 
2345 llvm::Value *
2346 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2347                                            bool isInc, bool isPre) {
2348 
2349   QualType type = E->getSubExpr()->getType();
2350   llvm::PHINode *atomicPHI = nullptr;
2351   llvm::Value *value;
2352   llvm::Value *input;
2353 
2354   int amount = (isInc ? 1 : -1);
2355   bool isSubtraction = !isInc;
2356 
2357   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2358     type = atomicTy->getValueType();
2359     if (isInc && type->isBooleanType()) {
2360       llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2361       if (isPre) {
2362         Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
2363           ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2364         return Builder.getTrue();
2365       }
2366       // For atomic bool increment, we just store true and return it for
2367       // preincrement, do an atomic swap with true for postincrement
2368       return Builder.CreateAtomicRMW(
2369           llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
2370           llvm::AtomicOrdering::SequentiallyConsistent);
2371     }
2372     // Special case for atomic increment / decrement on integers, emit
2373     // atomicrmw instructions.  We skip this if we want to be doing overflow
2374     // checking, and fall into the slow path with the atomic cmpxchg loop.
2375     if (!type->isBooleanType() && type->isIntegerType() &&
2376         !(type->isUnsignedIntegerType() &&
2377           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2378         CGF.getLangOpts().getSignedOverflowBehavior() !=
2379             LangOptions::SOB_Trapping) {
2380       llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2381         llvm::AtomicRMWInst::Sub;
2382       llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2383         llvm::Instruction::Sub;
2384       llvm::Value *amt = CGF.EmitToMemory(
2385           llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2386       llvm::Value *old = Builder.CreateAtomicRMW(aop,
2387           LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
2388       return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2389     }
2390     value = EmitLoadOfLValue(LV, E->getExprLoc());
2391     input = value;
2392     // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2393     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2394     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2395     value = CGF.EmitToMemory(value, type);
2396     Builder.CreateBr(opBB);
2397     Builder.SetInsertPoint(opBB);
2398     atomicPHI = Builder.CreatePHI(value->getType(), 2);
2399     atomicPHI->addIncoming(value, startBB);
2400     value = atomicPHI;
2401   } else {
2402     value = EmitLoadOfLValue(LV, E->getExprLoc());
2403     input = value;
2404   }
2405 
2406   // Special case of integer increment that we have to check first: bool++.
2407   // Due to promotion rules, we get:
2408   //   bool++ -> bool = bool + 1
2409   //          -> bool = (int)bool + 1
2410   //          -> bool = ((int)bool + 1 != 0)
2411   // An interesting aspect of this is that increment is always true.
2412   // Decrement does not have this property.
2413   if (isInc && type->isBooleanType()) {
2414     value = Builder.getTrue();
2415 
2416   // Most common case by far: integer increment.
2417   } else if (type->isIntegerType()) {
2418     // Note that signed integer inc/dec with width less than int can't
2419     // overflow because of promotion rules; we're just eliding a few steps here.
2420     if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2421       value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2422     } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2423                CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2424       value =
2425           EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
2426     } else {
2427       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2428       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2429     }
2430 
2431   // Next most common: pointer increment.
2432   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2433     QualType type = ptr->getPointeeType();
2434 
2435     // VLA types don't have constant size.
2436     if (const VariableArrayType *vla
2437           = CGF.getContext().getAsVariableArrayType(type)) {
2438       llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
2439       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
2440       if (CGF.getLangOpts().isSignedOverflowDefined())
2441         value = Builder.CreateGEP(value, numElts, "vla.inc");
2442       else
2443         value = CGF.EmitCheckedInBoundsGEP(
2444             value, numElts, /*SignedIndices=*/false, isSubtraction,
2445             E->getExprLoc(), "vla.inc");
2446 
2447     // Arithmetic on function pointers (!) is just +-1.
2448     } else if (type->isFunctionType()) {
2449       llvm::Value *amt = Builder.getInt32(amount);
2450 
2451       value = CGF.EmitCastToVoidPtr(value);
2452       if (CGF.getLangOpts().isSignedOverflowDefined())
2453         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2454       else
2455         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2456                                            isSubtraction, E->getExprLoc(),
2457                                            "incdec.funcptr");
2458       value = Builder.CreateBitCast(value, input->getType());
2459 
2460     // For everything else, we can just do a simple increment.
2461     } else {
2462       llvm::Value *amt = Builder.getInt32(amount);
2463       if (CGF.getLangOpts().isSignedOverflowDefined())
2464         value = Builder.CreateGEP(value, amt, "incdec.ptr");
2465       else
2466         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2467                                            isSubtraction, E->getExprLoc(),
2468                                            "incdec.ptr");
2469     }
2470 
2471   // Vector increment/decrement.
2472   } else if (type->isVectorType()) {
2473     if (type->hasIntegerRepresentation()) {
2474       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2475 
2476       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2477     } else {
2478       value = Builder.CreateFAdd(
2479                   value,
2480                   llvm::ConstantFP::get(value->getType(), amount),
2481                   isInc ? "inc" : "dec");
2482     }
2483 
2484   // Floating point.
2485   } else if (type->isRealFloatingType()) {
2486     // Add the inc/dec to the real part.
2487     llvm::Value *amt;
2488 
2489     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2490       // Another special case: half FP increment should be done via float
2491       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2492         value = Builder.CreateCall(
2493             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2494                                  CGF.CGM.FloatTy),
2495             input, "incdec.conv");
2496       } else {
2497         value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2498       }
2499     }
2500 
2501     if (value->getType()->isFloatTy())
2502       amt = llvm::ConstantFP::get(VMContext,
2503                                   llvm::APFloat(static_cast<float>(amount)));
2504     else if (value->getType()->isDoubleTy())
2505       amt = llvm::ConstantFP::get(VMContext,
2506                                   llvm::APFloat(static_cast<double>(amount)));
2507     else {
2508       // Remaining types are Half, LongDouble or __float128. Convert from float.
2509       llvm::APFloat F(static_cast<float>(amount));
2510       bool ignored;
2511       const llvm::fltSemantics *FS;
2512       // Don't use getFloatTypeSemantics because Half isn't
2513       // necessarily represented using the "half" LLVM type.
2514       if (value->getType()->isFP128Ty())
2515         FS = &CGF.getTarget().getFloat128Format();
2516       else if (value->getType()->isHalfTy())
2517         FS = &CGF.getTarget().getHalfFormat();
2518       else
2519         FS = &CGF.getTarget().getLongDoubleFormat();
2520       F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
2521       amt = llvm::ConstantFP::get(VMContext, F);
2522     }
2523     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2524 
2525     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2526       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2527         value = Builder.CreateCall(
2528             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2529                                  CGF.CGM.FloatTy),
2530             value, "incdec.conv");
2531       } else {
2532         value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2533       }
2534     }
2535 
2536   // Objective-C pointer types.
2537   } else {
2538     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2539     value = CGF.EmitCastToVoidPtr(value);
2540 
2541     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2542     if (!isInc) size = -size;
2543     llvm::Value *sizeValue =
2544       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2545 
2546     if (CGF.getLangOpts().isSignedOverflowDefined())
2547       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2548     else
2549       value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2550                                          /*SignedIndices=*/false, isSubtraction,
2551                                          E->getExprLoc(), "incdec.objptr");
2552     value = Builder.CreateBitCast(value, input->getType());
2553   }
2554 
2555   if (atomicPHI) {
2556     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
2557     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2558     auto Pair = CGF.EmitAtomicCompareExchange(
2559         LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2560     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2561     llvm::Value *success = Pair.second;
2562     atomicPHI->addIncoming(old, curBlock);
2563     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
2564     Builder.SetInsertPoint(contBB);
2565     return isPre ? value : input;
2566   }
2567 
2568   // Store the updated result through the lvalue.
2569   if (LV.isBitField())
2570     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
2571   else
2572     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
2573 
2574   // If this is a postinc, return the value read from memory, otherwise use the
2575   // updated value.
2576   return isPre ? value : input;
2577 }
2578 
2579 
2580 
2581 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
2582   TestAndClearIgnoreResultAssign();
2583   Value *Op = Visit(E->getSubExpr());
2584 
2585   // Generate a unary FNeg for FP ops.
2586   if (Op->getType()->isFPOrFPVectorTy())
2587     return Builder.CreateFNeg(Op, "fneg");
2588 
2589   // Emit unary minus with EmitSub so we handle overflow cases etc.
2590   BinOpInfo BinOp;
2591   BinOp.RHS = Op;
2592   BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2593   BinOp.Ty = E->getType();
2594   BinOp.Opcode = BO_Sub;
2595   // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2596   BinOp.E = E;
2597   return EmitSub(BinOp);
2598 }
2599 
2600 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2601   TestAndClearIgnoreResultAssign();
2602   Value *Op = Visit(E->getSubExpr());
2603   return Builder.CreateNot(Op, "neg");
2604 }
2605 
2606 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2607   // Perform vector logical not on comparison with zero vector.
2608   if (E->getType()->isExtVectorType()) {
2609     Value *Oper = Visit(E->getSubExpr());
2610     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2611     Value *Result;
2612     if (Oper->getType()->isFPOrFPVectorTy())
2613       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2614     else
2615       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2616     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2617   }
2618 
2619   // Compare operand to zero.
2620   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2621 
2622   // Invert value.
2623   // TODO: Could dynamically modify easy computations here.  For example, if
2624   // the operand is an icmp ne, turn into icmp eq.
2625   BoolVal = Builder.CreateNot(BoolVal, "lnot");
2626 
2627   // ZExt result to the expr type.
2628   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2629 }
2630 
2631 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2632   // Try folding the offsetof to a constant.
2633   Expr::EvalResult EVResult;
2634   if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2635     llvm::APSInt Value = EVResult.Val.getInt();
2636     return Builder.getInt(Value);
2637   }
2638 
2639   // Loop over the components of the offsetof to compute the value.
2640   unsigned n = E->getNumComponents();
2641   llvm::Type* ResultType = ConvertType(E->getType());
2642   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2643   QualType CurrentType = E->getTypeSourceInfo()->getType();
2644   for (unsigned i = 0; i != n; ++i) {
2645     OffsetOfNode ON = E->getComponent(i);
2646     llvm::Value *Offset = nullptr;
2647     switch (ON.getKind()) {
2648     case OffsetOfNode::Array: {
2649       // Compute the index
2650       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2651       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2652       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2653       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2654 
2655       // Save the element type
2656       CurrentType =
2657           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2658 
2659       // Compute the element size
2660       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2661           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2662 
2663       // Multiply out to compute the result
2664       Offset = Builder.CreateMul(Idx, ElemSize);
2665       break;
2666     }
2667 
2668     case OffsetOfNode::Field: {
2669       FieldDecl *MemberDecl = ON.getField();
2670       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2671       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2672 
2673       // Compute the index of the field in its parent.
2674       unsigned i = 0;
2675       // FIXME: It would be nice if we didn't have to loop here!
2676       for (RecordDecl::field_iterator Field = RD->field_begin(),
2677                                       FieldEnd = RD->field_end();
2678            Field != FieldEnd; ++Field, ++i) {
2679         if (*Field == MemberDecl)
2680           break;
2681       }
2682       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2683 
2684       // Compute the offset to the field
2685       int64_t OffsetInt = RL.getFieldOffset(i) /
2686                           CGF.getContext().getCharWidth();
2687       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2688 
2689       // Save the element type.
2690       CurrentType = MemberDecl->getType();
2691       break;
2692     }
2693 
2694     case OffsetOfNode::Identifier:
2695       llvm_unreachable("dependent __builtin_offsetof");
2696 
2697     case OffsetOfNode::Base: {
2698       if (ON.getBase()->isVirtual()) {
2699         CGF.ErrorUnsupported(E, "virtual base in offsetof");
2700         continue;
2701       }
2702 
2703       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2704       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2705 
2706       // Save the element type.
2707       CurrentType = ON.getBase()->getType();
2708 
2709       // Compute the offset to the base.
2710       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2711       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2712       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2713       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2714       break;
2715     }
2716     }
2717     Result = Builder.CreateAdd(Result, Offset);
2718   }
2719   return Result;
2720 }
2721 
2722 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2723 /// argument of the sizeof expression as an integer.
2724 Value *
2725 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2726                               const UnaryExprOrTypeTraitExpr *E) {
2727   QualType TypeToSize = E->getTypeOfArgument();
2728   if (E->getKind() == UETT_SizeOf) {
2729     if (const VariableArrayType *VAT =
2730           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2731       if (E->isArgumentType()) {
2732         // sizeof(type) - make sure to emit the VLA size.
2733         CGF.EmitVariablyModifiedType(TypeToSize);
2734       } else {
2735         // C99 6.5.3.4p2: If the argument is an expression of type
2736         // VLA, it is evaluated.
2737         CGF.EmitIgnoredExpr(E->getArgumentExpr());
2738       }
2739 
2740       auto VlaSize = CGF.getVLASize(VAT);
2741       llvm::Value *size = VlaSize.NumElts;
2742 
2743       // Scale the number of non-VLA elements by the non-VLA element size.
2744       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2745       if (!eltSize.isOne())
2746         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2747 
2748       return size;
2749     }
2750   } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2751     auto Alignment =
2752         CGF.getContext()
2753             .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2754                 E->getTypeOfArgument()->getPointeeType()))
2755             .getQuantity();
2756     return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2757   }
2758 
2759   // If this isn't sizeof(vla), the result must be constant; use the constant
2760   // folding logic so we don't have to duplicate it here.
2761   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2762 }
2763 
2764 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2765   Expr *Op = E->getSubExpr();
2766   if (Op->getType()->isAnyComplexType()) {
2767     // If it's an l-value, load through the appropriate subobject l-value.
2768     // Note that we have to ask E because Op might be an l-value that
2769     // this won't work for, e.g. an Obj-C property.
2770     if (E->isGLValue())
2771       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2772                                   E->getExprLoc()).getScalarVal();
2773 
2774     // Otherwise, calculate and project.
2775     return CGF.EmitComplexExpr(Op, false, true).first;
2776   }
2777 
2778   return Visit(Op);
2779 }
2780 
2781 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2782   Expr *Op = E->getSubExpr();
2783   if (Op->getType()->isAnyComplexType()) {
2784     // If it's an l-value, load through the appropriate subobject l-value.
2785     // Note that we have to ask E because Op might be an l-value that
2786     // this won't work for, e.g. an Obj-C property.
2787     if (Op->isGLValue())
2788       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2789                                   E->getExprLoc()).getScalarVal();
2790 
2791     // Otherwise, calculate and project.
2792     return CGF.EmitComplexExpr(Op, true, false).second;
2793   }
2794 
2795   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
2796   // effects are evaluated, but not the actual value.
2797   if (Op->isGLValue())
2798     CGF.EmitLValue(Op);
2799   else
2800     CGF.EmitScalarExpr(Op, true);
2801   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2802 }
2803 
2804 //===----------------------------------------------------------------------===//
2805 //                           Binary Operators
2806 //===----------------------------------------------------------------------===//
2807 
2808 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2809   TestAndClearIgnoreResultAssign();
2810   BinOpInfo Result;
2811   Result.LHS = Visit(E->getLHS());
2812   Result.RHS = Visit(E->getRHS());
2813   Result.Ty  = E->getType();
2814   Result.Opcode = E->getOpcode();
2815   Result.FPFeatures = E->getFPFeatures();
2816   Result.E = E;
2817   return Result;
2818 }
2819 
2820 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2821                                               const CompoundAssignOperator *E,
2822                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2823                                                    Value *&Result) {
2824   QualType LHSTy = E->getLHS()->getType();
2825   BinOpInfo OpInfo;
2826 
2827   if (E->getComputationResultType()->isAnyComplexType())
2828     return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2829 
2830   // Emit the RHS first.  __block variables need to have the rhs evaluated
2831   // first, plus this should improve codegen a little.
2832   OpInfo.RHS = Visit(E->getRHS());
2833   OpInfo.Ty = E->getComputationResultType();
2834   OpInfo.Opcode = E->getOpcode();
2835   OpInfo.FPFeatures = E->getFPFeatures();
2836   OpInfo.E = E;
2837   // Load/convert the LHS.
2838   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2839 
2840   llvm::PHINode *atomicPHI = nullptr;
2841   if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2842     QualType type = atomicTy->getValueType();
2843     if (!type->isBooleanType() && type->isIntegerType() &&
2844         !(type->isUnsignedIntegerType() &&
2845           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2846         CGF.getLangOpts().getSignedOverflowBehavior() !=
2847             LangOptions::SOB_Trapping) {
2848       llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2849       switch (OpInfo.Opcode) {
2850         // We don't have atomicrmw operands for *, %, /, <<, >>
2851         case BO_MulAssign: case BO_DivAssign:
2852         case BO_RemAssign:
2853         case BO_ShlAssign:
2854         case BO_ShrAssign:
2855           break;
2856         case BO_AddAssign:
2857           aop = llvm::AtomicRMWInst::Add;
2858           break;
2859         case BO_SubAssign:
2860           aop = llvm::AtomicRMWInst::Sub;
2861           break;
2862         case BO_AndAssign:
2863           aop = llvm::AtomicRMWInst::And;
2864           break;
2865         case BO_XorAssign:
2866           aop = llvm::AtomicRMWInst::Xor;
2867           break;
2868         case BO_OrAssign:
2869           aop = llvm::AtomicRMWInst::Or;
2870           break;
2871         default:
2872           llvm_unreachable("Invalid compound assignment type");
2873       }
2874       if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2875         llvm::Value *amt = CGF.EmitToMemory(
2876             EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
2877                                  E->getExprLoc()),
2878             LHSTy);
2879         Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
2880             llvm::AtomicOrdering::SequentiallyConsistent);
2881         return LHSLV;
2882       }
2883     }
2884     // FIXME: For floating point types, we should be saving and restoring the
2885     // floating point environment in the loop.
2886     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2887     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2888     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2889     OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
2890     Builder.CreateBr(opBB);
2891     Builder.SetInsertPoint(opBB);
2892     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2893     atomicPHI->addIncoming(OpInfo.LHS, startBB);
2894     OpInfo.LHS = atomicPHI;
2895   }
2896   else
2897     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
2898 
2899   SourceLocation Loc = E->getExprLoc();
2900   OpInfo.LHS =
2901       EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
2902 
2903   // Expand the binary operator.
2904   Result = (this->*Func)(OpInfo);
2905 
2906   // Convert the result back to the LHS type,
2907   // potentially with Implicit Conversion sanitizer check.
2908   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
2909                                 Loc, ScalarConversionOpts(CGF.SanOpts));
2910 
2911   if (atomicPHI) {
2912     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
2913     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2914     auto Pair = CGF.EmitAtomicCompareExchange(
2915         LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
2916     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
2917     llvm::Value *success = Pair.second;
2918     atomicPHI->addIncoming(old, curBlock);
2919     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
2920     Builder.SetInsertPoint(contBB);
2921     return LHSLV;
2922   }
2923 
2924   // Store the result value into the LHS lvalue. Bit-fields are handled
2925   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2926   // 'An assignment expression has the value of the left operand after the
2927   // assignment...'.
2928   if (LHSLV.isBitField())
2929     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2930   else
2931     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2932 
2933   return LHSLV;
2934 }
2935 
2936 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2937                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2938   bool Ignore = TestAndClearIgnoreResultAssign();
2939   Value *RHS = nullptr;
2940   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2941 
2942   // If the result is clearly ignored, return now.
2943   if (Ignore)
2944     return nullptr;
2945 
2946   // The result of an assignment in C is the assigned r-value.
2947   if (!CGF.getLangOpts().CPlusPlus)
2948     return RHS;
2949 
2950   // If the lvalue is non-volatile, return the computed value of the assignment.
2951   if (!LHS.isVolatileQualified())
2952     return RHS;
2953 
2954   // Otherwise, reload the value.
2955   return EmitLoadOfLValue(LHS, E->getExprLoc());
2956 }
2957 
2958 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2959     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2960   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
2961 
2962   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2963     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2964                                     SanitizerKind::IntegerDivideByZero));
2965   }
2966 
2967   const auto *BO = cast<BinaryOperator>(Ops.E);
2968   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
2969       Ops.Ty->hasSignedIntegerRepresentation() &&
2970       !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
2971       Ops.mayHaveIntegerOverflow()) {
2972     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2973 
2974     llvm::Value *IntMin =
2975       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2976     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2977 
2978     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2979     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2980     llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2981     Checks.push_back(
2982         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
2983   }
2984 
2985   if (Checks.size() > 0)
2986     EmitBinOpCheck(Checks, Ops);
2987 }
2988 
2989 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2990   {
2991     CodeGenFunction::SanitizerScope SanScope(&CGF);
2992     if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2993          CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2994         Ops.Ty->isIntegerType() &&
2995         (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
2996       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2997       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2998     } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2999                Ops.Ty->isRealFloatingType() &&
3000                Ops.mayHaveFloatDivisionByZero()) {
3001       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3002       llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3003       EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3004                      Ops);
3005     }
3006   }
3007 
3008   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3009     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3010     if (CGF.getLangOpts().OpenCL &&
3011         !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3012       // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3013       // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3014       // build option allows an application to specify that single precision
3015       // floating-point divide (x/y and 1/x) and sqrt used in the program
3016       // source are correctly rounded.
3017       llvm::Type *ValTy = Val->getType();
3018       if (ValTy->isFloatTy() ||
3019           (isa<llvm::VectorType>(ValTy) &&
3020            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
3021         CGF.SetFPAccuracy(Val, 2.5);
3022     }
3023     return Val;
3024   }
3025   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3026     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3027   else
3028     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3029 }
3030 
3031 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3032   // Rem in C can't be a floating point type: C99 6.5.5p2.
3033   if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3034        CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3035       Ops.Ty->isIntegerType() &&
3036       (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3037     CodeGenFunction::SanitizerScope SanScope(&CGF);
3038     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3039     EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3040   }
3041 
3042   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3043     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3044   else
3045     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3046 }
3047 
3048 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3049   unsigned IID;
3050   unsigned OpID = 0;
3051 
3052   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3053   switch (Ops.Opcode) {
3054   case BO_Add:
3055   case BO_AddAssign:
3056     OpID = 1;
3057     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3058                      llvm::Intrinsic::uadd_with_overflow;
3059     break;
3060   case BO_Sub:
3061   case BO_SubAssign:
3062     OpID = 2;
3063     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3064                      llvm::Intrinsic::usub_with_overflow;
3065     break;
3066   case BO_Mul:
3067   case BO_MulAssign:
3068     OpID = 3;
3069     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3070                      llvm::Intrinsic::umul_with_overflow;
3071     break;
3072   default:
3073     llvm_unreachable("Unsupported operation for overflow detection");
3074   }
3075   OpID <<= 1;
3076   if (isSigned)
3077     OpID |= 1;
3078 
3079   CodeGenFunction::SanitizerScope SanScope(&CGF);
3080   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3081 
3082   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3083 
3084   Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3085   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3086   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3087 
3088   // Handle overflow with llvm.trap if no custom handler has been specified.
3089   const std::string *handlerName =
3090     &CGF.getLangOpts().OverflowHandler;
3091   if (handlerName->empty()) {
3092     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3093     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3094     if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3095       llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3096       SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3097                               : SanitizerKind::UnsignedIntegerOverflow;
3098       EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3099     } else
3100       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
3101     return result;
3102   }
3103 
3104   // Branch in case of overflow.
3105   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3106   llvm::BasicBlock *continueBB =
3107       CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3108   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3109 
3110   Builder.CreateCondBr(overflow, overflowBB, continueBB);
3111 
3112   // If an overflow handler is set, then we want to call it and then use its
3113   // result, if it returns.
3114   Builder.SetInsertPoint(overflowBB);
3115 
3116   // Get the overflow handler.
3117   llvm::Type *Int8Ty = CGF.Int8Ty;
3118   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3119   llvm::FunctionType *handlerTy =
3120       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3121   llvm::FunctionCallee handler =
3122       CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3123 
3124   // Sign extend the args to 64-bit, so that we can use the same handler for
3125   // all types of overflow.
3126   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3127   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3128 
3129   // Call the handler with the two arguments, the operation, and the size of
3130   // the result.
3131   llvm::Value *handlerArgs[] = {
3132     lhs,
3133     rhs,
3134     Builder.getInt8(OpID),
3135     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3136   };
3137   llvm::Value *handlerResult =
3138     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3139 
3140   // Truncate the result back to the desired size.
3141   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3142   Builder.CreateBr(continueBB);
3143 
3144   Builder.SetInsertPoint(continueBB);
3145   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3146   phi->addIncoming(result, initialBB);
3147   phi->addIncoming(handlerResult, overflowBB);
3148 
3149   return phi;
3150 }
3151 
3152 /// Emit pointer + index arithmetic.
3153 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3154                                     const BinOpInfo &op,
3155                                     bool isSubtraction) {
3156   // Must have binary (not unary) expr here.  Unary pointer
3157   // increment/decrement doesn't use this path.
3158   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3159 
3160   Value *pointer = op.LHS;
3161   Expr *pointerOperand = expr->getLHS();
3162   Value *index = op.RHS;
3163   Expr *indexOperand = expr->getRHS();
3164 
3165   // In a subtraction, the LHS is always the pointer.
3166   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3167     std::swap(pointer, index);
3168     std::swap(pointerOperand, indexOperand);
3169   }
3170 
3171   bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3172 
3173   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3174   auto &DL = CGF.CGM.getDataLayout();
3175   auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3176 
3177   // Some versions of glibc and gcc use idioms (particularly in their malloc
3178   // routines) that add a pointer-sized integer (known to be a pointer value)
3179   // to a null pointer in order to cast the value back to an integer or as
3180   // part of a pointer alignment algorithm.  This is undefined behavior, but
3181   // we'd like to be able to compile programs that use it.
3182   //
3183   // Normally, we'd generate a GEP with a null-pointer base here in response
3184   // to that code, but it's also UB to dereference a pointer created that
3185   // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
3186   // generate a direct cast of the integer value to a pointer.
3187   //
3188   // The idiom (p = nullptr + N) is not met if any of the following are true:
3189   //
3190   //   The operation is subtraction.
3191   //   The index is not pointer-sized.
3192   //   The pointer type is not byte-sized.
3193   //
3194   if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3195                                                        op.Opcode,
3196                                                        expr->getLHS(),
3197                                                        expr->getRHS()))
3198     return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3199 
3200   if (width != DL.getTypeSizeInBits(PtrTy)) {
3201     // Zero-extend or sign-extend the pointer value according to
3202     // whether the index is signed or not.
3203     index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
3204                                       "idx.ext");
3205   }
3206 
3207   // If this is subtraction, negate the index.
3208   if (isSubtraction)
3209     index = CGF.Builder.CreateNeg(index, "idx.neg");
3210 
3211   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3212     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3213                         /*Accessed*/ false);
3214 
3215   const PointerType *pointerType
3216     = pointerOperand->getType()->getAs<PointerType>();
3217   if (!pointerType) {
3218     QualType objectType = pointerOperand->getType()
3219                                         ->castAs<ObjCObjectPointerType>()
3220                                         ->getPointeeType();
3221     llvm::Value *objectSize
3222       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3223 
3224     index = CGF.Builder.CreateMul(index, objectSize);
3225 
3226     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3227     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3228     return CGF.Builder.CreateBitCast(result, pointer->getType());
3229   }
3230 
3231   QualType elementType = pointerType->getPointeeType();
3232   if (const VariableArrayType *vla
3233         = CGF.getContext().getAsVariableArrayType(elementType)) {
3234     // The element count here is the total number of non-VLA elements.
3235     llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3236 
3237     // Effectively, the multiply by the VLA size is part of the GEP.
3238     // GEP indexes are signed, and scaling an index isn't permitted to
3239     // signed-overflow, so we use the same semantics for our explicit
3240     // multiply.  We suppress this if overflow is not undefined behavior.
3241     if (CGF.getLangOpts().isSignedOverflowDefined()) {
3242       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3243       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3244     } else {
3245       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3246       pointer =
3247           CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3248                                      op.E->getExprLoc(), "add.ptr");
3249     }
3250     return pointer;
3251   }
3252 
3253   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3254   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3255   // future proof.
3256   if (elementType->isVoidType() || elementType->isFunctionType()) {
3257     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3258     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3259     return CGF.Builder.CreateBitCast(result, pointer->getType());
3260   }
3261 
3262   if (CGF.getLangOpts().isSignedOverflowDefined())
3263     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3264 
3265   return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3266                                     op.E->getExprLoc(), "add.ptr");
3267 }
3268 
3269 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3270 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
3271 // the add operand respectively. This allows fmuladd to represent a*b-c, or
3272 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3273 // efficient operations.
3274 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
3275                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
3276                            bool negMul, bool negAdd) {
3277   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3278 
3279   Value *MulOp0 = MulOp->getOperand(0);
3280   Value *MulOp1 = MulOp->getOperand(1);
3281   if (negMul) {
3282     MulOp0 =
3283       Builder.CreateFSub(
3284         llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
3285         "neg");
3286   } else if (negAdd) {
3287     Addend =
3288       Builder.CreateFSub(
3289         llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
3290         "neg");
3291   }
3292 
3293   Value *FMulAdd = Builder.CreateCall(
3294       CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3295       {MulOp0, MulOp1, Addend});
3296    MulOp->eraseFromParent();
3297 
3298    return FMulAdd;
3299 }
3300 
3301 // Check whether it would be legal to emit an fmuladd intrinsic call to
3302 // represent op and if so, build the fmuladd.
3303 //
3304 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3305 // Does NOT check the type of the operation - it's assumed that this function
3306 // will be called from contexts where it's known that the type is contractable.
3307 static Value* tryEmitFMulAdd(const BinOpInfo &op,
3308                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
3309                          bool isSub=false) {
3310 
3311   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3312           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3313          "Only fadd/fsub can be the root of an fmuladd.");
3314 
3315   // Check whether this op is marked as fusable.
3316   if (!op.FPFeatures.allowFPContractWithinStatement())
3317     return nullptr;
3318 
3319   // We have a potentially fusable op. Look for a mul on one of the operands.
3320   // Also, make sure that the mul result isn't used directly. In that case,
3321   // there's no point creating a muladd operation.
3322   if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3323     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3324         LHSBinOp->use_empty())
3325       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3326   }
3327   if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3328     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3329         RHSBinOp->use_empty())
3330       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3331   }
3332 
3333   return nullptr;
3334 }
3335 
3336 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3337   if (op.LHS->getType()->isPointerTy() ||
3338       op.RHS->getType()->isPointerTy())
3339     return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3340 
3341   if (op.Ty->isSignedIntegerOrEnumerationType()) {
3342     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3343     case LangOptions::SOB_Defined:
3344       return Builder.CreateAdd(op.LHS, op.RHS, "add");
3345     case LangOptions::SOB_Undefined:
3346       if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3347         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3348       LLVM_FALLTHROUGH;
3349     case LangOptions::SOB_Trapping:
3350       if (CanElideOverflowCheck(CGF.getContext(), op))
3351         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3352       return EmitOverflowCheckedBinOp(op);
3353     }
3354   }
3355 
3356   if (op.Ty->isUnsignedIntegerType() &&
3357       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3358       !CanElideOverflowCheck(CGF.getContext(), op))
3359     return EmitOverflowCheckedBinOp(op);
3360 
3361   if (op.LHS->getType()->isFPOrFPVectorTy()) {
3362     // Try to form an fmuladd.
3363     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3364       return FMulAdd;
3365 
3366     Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
3367     return propagateFMFlags(V, op);
3368   }
3369 
3370   if (op.isFixedPointBinOp())
3371     return EmitFixedPointBinOp(op);
3372 
3373   return Builder.CreateAdd(op.LHS, op.RHS, "add");
3374 }
3375 
3376 /// The resulting value must be calculated with exact precision, so the operands
3377 /// may not be the same type.
3378 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3379   using llvm::APSInt;
3380   using llvm::ConstantInt;
3381 
3382   const auto *BinOp = cast<BinaryOperator>(op.E);
3383 
3384   // The result is a fixed point type and at least one of the operands is fixed
3385   // point while the other is either fixed point or an int. This resulting type
3386   // should be determined by Sema::handleFixedPointConversions().
3387   QualType ResultTy = op.Ty;
3388   QualType LHSTy = BinOp->getLHS()->getType();
3389   QualType RHSTy = BinOp->getRHS()->getType();
3390   ASTContext &Ctx = CGF.getContext();
3391   Value *LHS = op.LHS;
3392   Value *RHS = op.RHS;
3393 
3394   auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3395   auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3396   auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3397   auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3398 
3399   // Convert the operands to the full precision type.
3400   Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
3401                                             BinOp->getExprLoc());
3402   Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
3403                                             BinOp->getExprLoc());
3404 
3405   // Perform the actual addition.
3406   Value *Result;
3407   switch (BinOp->getOpcode()) {
3408   case BO_Add: {
3409     if (ResultFixedSema.isSaturated()) {
3410       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3411                                     ? llvm::Intrinsic::sadd_sat
3412                                     : llvm::Intrinsic::uadd_sat;
3413       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3414     } else {
3415       Result = Builder.CreateAdd(FullLHS, FullRHS);
3416     }
3417     break;
3418   }
3419   case BO_Sub: {
3420     if (ResultFixedSema.isSaturated()) {
3421       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3422                                     ? llvm::Intrinsic::ssub_sat
3423                                     : llvm::Intrinsic::usub_sat;
3424       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3425     } else {
3426       Result = Builder.CreateSub(FullLHS, FullRHS);
3427     }
3428     break;
3429   }
3430   case BO_LT:
3431     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3432                                       : Builder.CreateICmpULT(FullLHS, FullRHS);
3433   case BO_GT:
3434     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3435                                       : Builder.CreateICmpUGT(FullLHS, FullRHS);
3436   case BO_LE:
3437     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3438                                       : Builder.CreateICmpULE(FullLHS, FullRHS);
3439   case BO_GE:
3440     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3441                                       : Builder.CreateICmpUGE(FullLHS, FullRHS);
3442   case BO_EQ:
3443     // For equality operations, we assume any padding bits on unsigned types are
3444     // zero'd out. They could be overwritten through non-saturating operations
3445     // that cause overflow, but this leads to undefined behavior.
3446     return Builder.CreateICmpEQ(FullLHS, FullRHS);
3447   case BO_NE:
3448     return Builder.CreateICmpNE(FullLHS, FullRHS);
3449   case BO_Mul:
3450   case BO_Div:
3451   case BO_Shl:
3452   case BO_Shr:
3453   case BO_Cmp:
3454   case BO_LAnd:
3455   case BO_LOr:
3456   case BO_MulAssign:
3457   case BO_DivAssign:
3458   case BO_AddAssign:
3459   case BO_SubAssign:
3460   case BO_ShlAssign:
3461   case BO_ShrAssign:
3462     llvm_unreachable("Found unimplemented fixed point binary operation");
3463   case BO_PtrMemD:
3464   case BO_PtrMemI:
3465   case BO_Rem:
3466   case BO_Xor:
3467   case BO_And:
3468   case BO_Or:
3469   case BO_Assign:
3470   case BO_RemAssign:
3471   case BO_AndAssign:
3472   case BO_XorAssign:
3473   case BO_OrAssign:
3474   case BO_Comma:
3475     llvm_unreachable("Found unsupported binary operation for fixed point types.");
3476   }
3477 
3478   // Convert to the result type.
3479   return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
3480                                   BinOp->getExprLoc());
3481 }
3482 
3483 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3484   // The LHS is always a pointer if either side is.
3485   if (!op.LHS->getType()->isPointerTy()) {
3486     if (op.Ty->isSignedIntegerOrEnumerationType()) {
3487       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3488       case LangOptions::SOB_Defined:
3489         return Builder.CreateSub(op.LHS, op.RHS, "sub");
3490       case LangOptions::SOB_Undefined:
3491         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3492           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3493         LLVM_FALLTHROUGH;
3494       case LangOptions::SOB_Trapping:
3495         if (CanElideOverflowCheck(CGF.getContext(), op))
3496           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3497         return EmitOverflowCheckedBinOp(op);
3498       }
3499     }
3500 
3501     if (op.Ty->isUnsignedIntegerType() &&
3502         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3503         !CanElideOverflowCheck(CGF.getContext(), op))
3504       return EmitOverflowCheckedBinOp(op);
3505 
3506     if (op.LHS->getType()->isFPOrFPVectorTy()) {
3507       // Try to form an fmuladd.
3508       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3509         return FMulAdd;
3510       Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
3511       return propagateFMFlags(V, op);
3512     }
3513 
3514     if (op.isFixedPointBinOp())
3515       return EmitFixedPointBinOp(op);
3516 
3517     return Builder.CreateSub(op.LHS, op.RHS, "sub");
3518   }
3519 
3520   // If the RHS is not a pointer, then we have normal pointer
3521   // arithmetic.
3522   if (!op.RHS->getType()->isPointerTy())
3523     return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3524 
3525   // Otherwise, this is a pointer subtraction.
3526 
3527   // Do the raw subtraction part.
3528   llvm::Value *LHS
3529     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3530   llvm::Value *RHS
3531     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3532   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3533 
3534   // Okay, figure out the element size.
3535   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3536   QualType elementType = expr->getLHS()->getType()->getPointeeType();
3537 
3538   llvm::Value *divisor = nullptr;
3539 
3540   // For a variable-length array, this is going to be non-constant.
3541   if (const VariableArrayType *vla
3542         = CGF.getContext().getAsVariableArrayType(elementType)) {
3543     auto VlaSize = CGF.getVLASize(vla);
3544     elementType = VlaSize.Type;
3545     divisor = VlaSize.NumElts;
3546 
3547     // Scale the number of non-VLA elements by the non-VLA element size.
3548     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3549     if (!eltSize.isOne())
3550       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3551 
3552   // For everything elese, we can just compute it, safe in the
3553   // assumption that Sema won't let anything through that we can't
3554   // safely compute the size of.
3555   } else {
3556     CharUnits elementSize;
3557     // Handle GCC extension for pointer arithmetic on void* and
3558     // function pointer types.
3559     if (elementType->isVoidType() || elementType->isFunctionType())
3560       elementSize = CharUnits::One();
3561     else
3562       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3563 
3564     // Don't even emit the divide for element size of 1.
3565     if (elementSize.isOne())
3566       return diffInChars;
3567 
3568     divisor = CGF.CGM.getSize(elementSize);
3569   }
3570 
3571   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3572   // pointer difference in C is only defined in the case where both operands
3573   // are pointing to elements of an array.
3574   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3575 }
3576 
3577 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3578   llvm::IntegerType *Ty;
3579   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3580     Ty = cast<llvm::IntegerType>(VT->getElementType());
3581   else
3582     Ty = cast<llvm::IntegerType>(LHS->getType());
3583   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3584 }
3585 
3586 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3587   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3588   // RHS to the same size as the LHS.
3589   Value *RHS = Ops.RHS;
3590   if (Ops.LHS->getType() != RHS->getType())
3591     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3592 
3593   bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3594                       Ops.Ty->hasSignedIntegerRepresentation() &&
3595                       !CGF.getLangOpts().isSignedOverflowDefined() &&
3596                       !CGF.getLangOpts().CPlusPlus2a;
3597   bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3598   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3599   if (CGF.getLangOpts().OpenCL)
3600     RHS =
3601         Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
3602   else if ((SanitizeBase || SanitizeExponent) &&
3603            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3604     CodeGenFunction::SanitizerScope SanScope(&CGF);
3605     SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3606     llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3607     llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3608 
3609     if (SanitizeExponent) {
3610       Checks.push_back(
3611           std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3612     }
3613 
3614     if (SanitizeBase) {
3615       // Check whether we are shifting any non-zero bits off the top of the
3616       // integer. We only emit this check if exponent is valid - otherwise
3617       // instructions below will have undefined behavior themselves.
3618       llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3619       llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3620       llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3621       Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3622       llvm::Value *PromotedWidthMinusOne =
3623           (RHS == Ops.RHS) ? WidthMinusOne
3624                            : GetWidthMinusOneValue(Ops.LHS, RHS);
3625       CGF.EmitBlock(CheckShiftBase);
3626       llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3627           Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3628                                      /*NUW*/ true, /*NSW*/ true),
3629           "shl.check");
3630       if (CGF.getLangOpts().CPlusPlus) {
3631         // In C99, we are not permitted to shift a 1 bit into the sign bit.
3632         // Under C++11's rules, shifting a 1 bit into the sign bit is
3633         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3634         // define signed left shifts, so we use the C99 and C++11 rules there).
3635         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3636         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3637       }
3638       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3639       llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3640       CGF.EmitBlock(Cont);
3641       llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3642       BaseCheck->addIncoming(Builder.getTrue(), Orig);
3643       BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3644       Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
3645     }
3646 
3647     assert(!Checks.empty());
3648     EmitBinOpCheck(Checks, Ops);
3649   }
3650 
3651   return Builder.CreateShl(Ops.LHS, RHS, "shl");
3652 }
3653 
3654 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3655   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3656   // RHS to the same size as the LHS.
3657   Value *RHS = Ops.RHS;
3658   if (Ops.LHS->getType() != RHS->getType())
3659     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3660 
3661   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3662   if (CGF.getLangOpts().OpenCL)
3663     RHS =
3664         Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
3665   else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3666            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3667     CodeGenFunction::SanitizerScope SanScope(&CGF);
3668     llvm::Value *Valid =
3669         Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3670     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3671   }
3672 
3673   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3674     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3675   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3676 }
3677 
3678 enum IntrinsicType { VCMPEQ, VCMPGT };
3679 // return corresponding comparison intrinsic for given vector type
3680 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3681                                         BuiltinType::Kind ElemKind) {
3682   switch (ElemKind) {
3683   default: llvm_unreachable("unexpected element type");
3684   case BuiltinType::Char_U:
3685   case BuiltinType::UChar:
3686     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3687                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
3688   case BuiltinType::Char_S:
3689   case BuiltinType::SChar:
3690     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3691                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
3692   case BuiltinType::UShort:
3693     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3694                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
3695   case BuiltinType::Short:
3696     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3697                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
3698   case BuiltinType::UInt:
3699     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3700                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
3701   case BuiltinType::Int:
3702     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3703                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
3704   case BuiltinType::ULong:
3705   case BuiltinType::ULongLong:
3706     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3707                             llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3708   case BuiltinType::Long:
3709   case BuiltinType::LongLong:
3710     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3711                             llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
3712   case BuiltinType::Float:
3713     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3714                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
3715   case BuiltinType::Double:
3716     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3717                             llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
3718   }
3719 }
3720 
3721 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3722                                       llvm::CmpInst::Predicate UICmpOpc,
3723                                       llvm::CmpInst::Predicate SICmpOpc,
3724                                       llvm::CmpInst::Predicate FCmpOpc) {
3725   TestAndClearIgnoreResultAssign();
3726   Value *Result;
3727   QualType LHSTy = E->getLHS()->getType();
3728   QualType RHSTy = E->getRHS()->getType();
3729   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
3730     assert(E->getOpcode() == BO_EQ ||
3731            E->getOpcode() == BO_NE);
3732     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3733     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
3734     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
3735                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
3736   } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
3737     BinOpInfo BOInfo = EmitBinOps(E);
3738     Value *LHS = BOInfo.LHS;
3739     Value *RHS = BOInfo.RHS;
3740 
3741     // If AltiVec, the comparison results in a numeric type, so we use
3742     // intrinsics comparing vectors and giving 0 or 1 as a result
3743     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
3744       // constants for mapping CR6 register bits to predicate result
3745       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3746 
3747       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3748 
3749       // in several cases vector arguments order will be reversed
3750       Value *FirstVecArg = LHS,
3751             *SecondVecArg = RHS;
3752 
3753       QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
3754       const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
3755       BuiltinType::Kind ElementKind = BTy->getKind();
3756 
3757       switch(E->getOpcode()) {
3758       default: llvm_unreachable("is not a comparison operation");
3759       case BO_EQ:
3760         CR6 = CR6_LT;
3761         ID = GetIntrinsic(VCMPEQ, ElementKind);
3762         break;
3763       case BO_NE:
3764         CR6 = CR6_EQ;
3765         ID = GetIntrinsic(VCMPEQ, ElementKind);
3766         break;
3767       case BO_LT:
3768         CR6 = CR6_LT;
3769         ID = GetIntrinsic(VCMPGT, ElementKind);
3770         std::swap(FirstVecArg, SecondVecArg);
3771         break;
3772       case BO_GT:
3773         CR6 = CR6_LT;
3774         ID = GetIntrinsic(VCMPGT, ElementKind);
3775         break;
3776       case BO_LE:
3777         if (ElementKind == BuiltinType::Float) {
3778           CR6 = CR6_LT;
3779           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3780           std::swap(FirstVecArg, SecondVecArg);
3781         }
3782         else {
3783           CR6 = CR6_EQ;
3784           ID = GetIntrinsic(VCMPGT, ElementKind);
3785         }
3786         break;
3787       case BO_GE:
3788         if (ElementKind == BuiltinType::Float) {
3789           CR6 = CR6_LT;
3790           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3791         }
3792         else {
3793           CR6 = CR6_EQ;
3794           ID = GetIntrinsic(VCMPGT, ElementKind);
3795           std::swap(FirstVecArg, SecondVecArg);
3796         }
3797         break;
3798       }
3799 
3800       Value *CR6Param = Builder.getInt32(CR6);
3801       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
3802       Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
3803 
3804       // The result type of intrinsic may not be same as E->getType().
3805       // If E->getType() is not BoolTy, EmitScalarConversion will do the
3806       // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3807       // do nothing, if ResultTy is not i1 at the same time, it will cause
3808       // crash later.
3809       llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3810       if (ResultTy->getBitWidth() > 1 &&
3811           E->getType() == CGF.getContext().BoolTy)
3812         Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
3813       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3814                                   E->getExprLoc());
3815     }
3816 
3817     if (BOInfo.isFixedPointBinOp()) {
3818       Result = EmitFixedPointBinOp(BOInfo);
3819     } else if (LHS->getType()->isFPOrFPVectorTy()) {
3820       Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
3821     } else if (LHSTy->hasSignedIntegerRepresentation()) {
3822       Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
3823     } else {
3824       // Unsigned integers and pointers.
3825 
3826       if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
3827           !isa<llvm::ConstantPointerNull>(LHS) &&
3828           !isa<llvm::ConstantPointerNull>(RHS)) {
3829 
3830         // Dynamic information is required to be stripped for comparisons,
3831         // because it could leak the dynamic information.  Based on comparisons
3832         // of pointers to dynamic objects, the optimizer can replace one pointer
3833         // with another, which might be incorrect in presence of invariant
3834         // groups. Comparison with null is safe because null does not carry any
3835         // dynamic information.
3836         if (LHSTy.mayBeDynamicClass())
3837           LHS = Builder.CreateStripInvariantGroup(LHS);
3838         if (RHSTy.mayBeDynamicClass())
3839           RHS = Builder.CreateStripInvariantGroup(RHS);
3840       }
3841 
3842       Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
3843     }
3844 
3845     // If this is a vector comparison, sign extend the result to the appropriate
3846     // vector integer type and return it (don't convert to bool).
3847     if (LHSTy->isVectorType())
3848       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
3849 
3850   } else {
3851     // Complex Comparison: can only be an equality comparison.
3852     CodeGenFunction::ComplexPairTy LHS, RHS;
3853     QualType CETy;
3854     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
3855       LHS = CGF.EmitComplexExpr(E->getLHS());
3856       CETy = CTy->getElementType();
3857     } else {
3858       LHS.first = Visit(E->getLHS());
3859       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
3860       CETy = LHSTy;
3861     }
3862     if (auto *CTy = RHSTy->getAs<ComplexType>()) {
3863       RHS = CGF.EmitComplexExpr(E->getRHS());
3864       assert(CGF.getContext().hasSameUnqualifiedType(CETy,
3865                                                      CTy->getElementType()) &&
3866              "The element types must always match.");
3867       (void)CTy;
3868     } else {
3869       RHS.first = Visit(E->getRHS());
3870       RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
3871       assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
3872              "The element types must always match.");
3873     }
3874 
3875     Value *ResultR, *ResultI;
3876     if (CETy->isRealFloatingType()) {
3877       ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
3878       ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
3879     } else {
3880       // Complex comparisons can only be equality comparisons.  As such, signed
3881       // and unsigned opcodes are the same.
3882       ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
3883       ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
3884     }
3885 
3886     if (E->getOpcode() == BO_EQ) {
3887       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
3888     } else {
3889       assert(E->getOpcode() == BO_NE &&
3890              "Complex comparison other than == or != ?");
3891       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
3892     }
3893   }
3894 
3895   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3896                               E->getExprLoc());
3897 }
3898 
3899 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
3900   bool Ignore = TestAndClearIgnoreResultAssign();
3901 
3902   Value *RHS;
3903   LValue LHS;
3904 
3905   switch (E->getLHS()->getType().getObjCLifetime()) {
3906   case Qualifiers::OCL_Strong:
3907     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
3908     break;
3909 
3910   case Qualifiers::OCL_Autoreleasing:
3911     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
3912     break;
3913 
3914   case Qualifiers::OCL_ExplicitNone:
3915     std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
3916     break;
3917 
3918   case Qualifiers::OCL_Weak:
3919     RHS = Visit(E->getRHS());
3920     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3921     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
3922     break;
3923 
3924   case Qualifiers::OCL_None:
3925     // __block variables need to have the rhs evaluated first, plus
3926     // this should improve codegen just a little.
3927     RHS = Visit(E->getRHS());
3928     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
3929 
3930     // Store the value into the LHS.  Bit-fields are handled specially
3931     // because the result is altered by the store, i.e., [C99 6.5.16p1]
3932     // 'An assignment expression has the value of the left operand after
3933     // the assignment...'.
3934     if (LHS.isBitField()) {
3935       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
3936     } else {
3937       CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
3938       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
3939     }
3940   }
3941 
3942   // If the result is clearly ignored, return now.
3943   if (Ignore)
3944     return nullptr;
3945 
3946   // The result of an assignment in C is the assigned r-value.
3947   if (!CGF.getLangOpts().CPlusPlus)
3948     return RHS;
3949 
3950   // If the lvalue is non-volatile, return the computed value of the assignment.
3951   if (!LHS.isVolatileQualified())
3952     return RHS;
3953 
3954   // Otherwise, reload the value.
3955   return EmitLoadOfLValue(LHS, E->getExprLoc());
3956 }
3957 
3958 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
3959   // Perform vector logical and on comparisons with zero vectors.
3960   if (E->getType()->isVectorType()) {
3961     CGF.incrementProfileCounter(E);
3962 
3963     Value *LHS = Visit(E->getLHS());
3964     Value *RHS = Visit(E->getRHS());
3965     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
3966     if (LHS->getType()->isFPOrFPVectorTy()) {
3967       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3968       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3969     } else {
3970       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3971       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3972     }
3973     Value *And = Builder.CreateAnd(LHS, RHS);
3974     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
3975   }
3976 
3977   llvm::Type *ResTy = ConvertType(E->getType());
3978 
3979   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3980   // If we have 1 && X, just emit X without inserting the control flow.
3981   bool LHSCondVal;
3982   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3983     if (LHSCondVal) { // If we have 1 && X, just emit X.
3984       CGF.incrementProfileCounter(E);
3985 
3986       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
3987       // ZExt result to int or bool.
3988       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
3989     }
3990 
3991     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
3992     if (!CGF.ContainsLabel(E->getRHS()))
3993       return llvm::Constant::getNullValue(ResTy);
3994   }
3995 
3996   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3997   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
3998 
3999   CodeGenFunction::ConditionalEvaluation eval(CGF);
4000 
4001   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
4002   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4003                            CGF.getProfileCount(E->getRHS()));
4004 
4005   // Any edges into the ContBlock are now from an (indeterminate number of)
4006   // edges from this first condition.  All of these values will be false.  Start
4007   // setting up the PHI node in the Cont Block for this.
4008   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4009                                             "", ContBlock);
4010   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4011        PI != PE; ++PI)
4012     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
4013 
4014   eval.begin(CGF);
4015   CGF.EmitBlock(RHSBlock);
4016   CGF.incrementProfileCounter(E);
4017   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4018   eval.end(CGF);
4019 
4020   // Reaquire the RHS block, as there may be subblocks inserted.
4021   RHSBlock = Builder.GetInsertBlock();
4022 
4023   // Emit an unconditional branch from this block to ContBlock.
4024   {
4025     // There is no need to emit line number for unconditional branch.
4026     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4027     CGF.EmitBlock(ContBlock);
4028   }
4029   // Insert an entry into the phi node for the edge with the value of RHSCond.
4030   PN->addIncoming(RHSCond, RHSBlock);
4031 
4032   // Artificial location to preserve the scope information
4033   {
4034     auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4035     PN->setDebugLoc(Builder.getCurrentDebugLocation());
4036   }
4037 
4038   // ZExt result to int.
4039   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4040 }
4041 
4042 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4043   // Perform vector logical or on comparisons with zero vectors.
4044   if (E->getType()->isVectorType()) {
4045     CGF.incrementProfileCounter(E);
4046 
4047     Value *LHS = Visit(E->getLHS());
4048     Value *RHS = Visit(E->getRHS());
4049     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4050     if (LHS->getType()->isFPOrFPVectorTy()) {
4051       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4052       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4053     } else {
4054       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4055       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4056     }
4057     Value *Or = Builder.CreateOr(LHS, RHS);
4058     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4059   }
4060 
4061   llvm::Type *ResTy = ConvertType(E->getType());
4062 
4063   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4064   // If we have 0 || X, just emit X without inserting the control flow.
4065   bool LHSCondVal;
4066   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4067     if (!LHSCondVal) { // If we have 0 || X, just emit X.
4068       CGF.incrementProfileCounter(E);
4069 
4070       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4071       // ZExt result to int or bool.
4072       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4073     }
4074 
4075     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4076     if (!CGF.ContainsLabel(E->getRHS()))
4077       return llvm::ConstantInt::get(ResTy, 1);
4078   }
4079 
4080   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4081   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4082 
4083   CodeGenFunction::ConditionalEvaluation eval(CGF);
4084 
4085   // Branch on the LHS first.  If it is true, go to the success (cont) block.
4086   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4087                            CGF.getCurrentProfileCount() -
4088                                CGF.getProfileCount(E->getRHS()));
4089 
4090   // Any edges into the ContBlock are now from an (indeterminate number of)
4091   // edges from this first condition.  All of these values will be true.  Start
4092   // setting up the PHI node in the Cont Block for this.
4093   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4094                                             "", ContBlock);
4095   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4096        PI != PE; ++PI)
4097     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4098 
4099   eval.begin(CGF);
4100 
4101   // Emit the RHS condition as a bool value.
4102   CGF.EmitBlock(RHSBlock);
4103   CGF.incrementProfileCounter(E);
4104   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4105 
4106   eval.end(CGF);
4107 
4108   // Reaquire the RHS block, as there may be subblocks inserted.
4109   RHSBlock = Builder.GetInsertBlock();
4110 
4111   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
4112   // into the phi node for the edge with the value of RHSCond.
4113   CGF.EmitBlock(ContBlock);
4114   PN->addIncoming(RHSCond, RHSBlock);
4115 
4116   // ZExt result to int.
4117   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4118 }
4119 
4120 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4121   CGF.EmitIgnoredExpr(E->getLHS());
4122   CGF.EnsureInsertPoint();
4123   return Visit(E->getRHS());
4124 }
4125 
4126 //===----------------------------------------------------------------------===//
4127 //                             Other Operators
4128 //===----------------------------------------------------------------------===//
4129 
4130 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4131 /// expression is cheap enough and side-effect-free enough to evaluate
4132 /// unconditionally instead of conditionally.  This is used to convert control
4133 /// flow into selects in some cases.
4134 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4135                                                    CodeGenFunction &CGF) {
4136   // Anything that is an integer or floating point constant is fine.
4137   return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4138 
4139   // Even non-volatile automatic variables can't be evaluated unconditionally.
4140   // Referencing a thread_local may cause non-trivial initialization work to
4141   // occur. If we're inside a lambda and one of the variables is from the scope
4142   // outside the lambda, that function may have returned already. Reading its
4143   // locals is a bad idea. Also, these reads may introduce races there didn't
4144   // exist in the source-level program.
4145 }
4146 
4147 
4148 Value *ScalarExprEmitter::
4149 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4150   TestAndClearIgnoreResultAssign();
4151 
4152   // Bind the common expression if necessary.
4153   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4154 
4155   Expr *condExpr = E->getCond();
4156   Expr *lhsExpr = E->getTrueExpr();
4157   Expr *rhsExpr = E->getFalseExpr();
4158 
4159   // If the condition constant folds and can be elided, try to avoid emitting
4160   // the condition and the dead arm.
4161   bool CondExprBool;
4162   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4163     Expr *live = lhsExpr, *dead = rhsExpr;
4164     if (!CondExprBool) std::swap(live, dead);
4165 
4166     // If the dead side doesn't have labels we need, just emit the Live part.
4167     if (!CGF.ContainsLabel(dead)) {
4168       if (CondExprBool)
4169         CGF.incrementProfileCounter(E);
4170       Value *Result = Visit(live);
4171 
4172       // If the live part is a throw expression, it acts like it has a void
4173       // type, so evaluating it returns a null Value*.  However, a conditional
4174       // with non-void type must return a non-null Value*.
4175       if (!Result && !E->getType()->isVoidType())
4176         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4177 
4178       return Result;
4179     }
4180   }
4181 
4182   // OpenCL: If the condition is a vector, we can treat this condition like
4183   // the select function.
4184   if (CGF.getLangOpts().OpenCL
4185       && condExpr->getType()->isVectorType()) {
4186     CGF.incrementProfileCounter(E);
4187 
4188     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4189     llvm::Value *LHS = Visit(lhsExpr);
4190     llvm::Value *RHS = Visit(rhsExpr);
4191 
4192     llvm::Type *condType = ConvertType(condExpr->getType());
4193     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
4194 
4195     unsigned numElem = vecTy->getNumElements();
4196     llvm::Type *elemType = vecTy->getElementType();
4197 
4198     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4199     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4200     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
4201                                           llvm::VectorType::get(elemType,
4202                                                                 numElem),
4203                                           "sext");
4204     llvm::Value *tmp2 = Builder.CreateNot(tmp);
4205 
4206     // Cast float to int to perform ANDs if necessary.
4207     llvm::Value *RHSTmp = RHS;
4208     llvm::Value *LHSTmp = LHS;
4209     bool wasCast = false;
4210     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4211     if (rhsVTy->getElementType()->isFloatingPointTy()) {
4212       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4213       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4214       wasCast = true;
4215     }
4216 
4217     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4218     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4219     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4220     if (wasCast)
4221       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4222 
4223     return tmp5;
4224   }
4225 
4226   // If this is a really simple expression (like x ? 4 : 5), emit this as a
4227   // select instead of as control flow.  We can only do this if it is cheap and
4228   // safe to evaluate the LHS and RHS unconditionally.
4229   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4230       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4231     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4232     llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4233 
4234     CGF.incrementProfileCounter(E, StepV);
4235 
4236     llvm::Value *LHS = Visit(lhsExpr);
4237     llvm::Value *RHS = Visit(rhsExpr);
4238     if (!LHS) {
4239       // If the conditional has void type, make sure we return a null Value*.
4240       assert(!RHS && "LHS and RHS types must match");
4241       return nullptr;
4242     }
4243     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4244   }
4245 
4246   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4247   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4248   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4249 
4250   CodeGenFunction::ConditionalEvaluation eval(CGF);
4251   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4252                            CGF.getProfileCount(lhsExpr));
4253 
4254   CGF.EmitBlock(LHSBlock);
4255   CGF.incrementProfileCounter(E);
4256   eval.begin(CGF);
4257   Value *LHS = Visit(lhsExpr);
4258   eval.end(CGF);
4259 
4260   LHSBlock = Builder.GetInsertBlock();
4261   Builder.CreateBr(ContBlock);
4262 
4263   CGF.EmitBlock(RHSBlock);
4264   eval.begin(CGF);
4265   Value *RHS = Visit(rhsExpr);
4266   eval.end(CGF);
4267 
4268   RHSBlock = Builder.GetInsertBlock();
4269   CGF.EmitBlock(ContBlock);
4270 
4271   // If the LHS or RHS is a throw expression, it will be legitimately null.
4272   if (!LHS)
4273     return RHS;
4274   if (!RHS)
4275     return LHS;
4276 
4277   // Create a PHI node for the real part.
4278   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4279   PN->addIncoming(LHS, LHSBlock);
4280   PN->addIncoming(RHS, RHSBlock);
4281   return PN;
4282 }
4283 
4284 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4285   return Visit(E->getChosenSubExpr());
4286 }
4287 
4288 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4289   QualType Ty = VE->getType();
4290 
4291   if (Ty->isVariablyModifiedType())
4292     CGF.EmitVariablyModifiedType(Ty);
4293 
4294   Address ArgValue = Address::invalid();
4295   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4296 
4297   llvm::Type *ArgTy = ConvertType(VE->getType());
4298 
4299   // If EmitVAArg fails, emit an error.
4300   if (!ArgPtr.isValid()) {
4301     CGF.ErrorUnsupported(VE, "va_arg expression");
4302     return llvm::UndefValue::get(ArgTy);
4303   }
4304 
4305   // FIXME Volatility.
4306   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4307 
4308   // If EmitVAArg promoted the type, we must truncate it.
4309   if (ArgTy != Val->getType()) {
4310     if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4311       Val = Builder.CreateIntToPtr(Val, ArgTy);
4312     else
4313       Val = Builder.CreateTrunc(Val, ArgTy);
4314   }
4315 
4316   return Val;
4317 }
4318 
4319 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4320   return CGF.EmitBlockLiteral(block);
4321 }
4322 
4323 // Convert a vec3 to vec4, or vice versa.
4324 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4325                                  Value *Src, unsigned NumElementsDst) {
4326   llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4327   SmallVector<llvm::Constant*, 4> Args;
4328   Args.push_back(Builder.getInt32(0));
4329   Args.push_back(Builder.getInt32(1));
4330   Args.push_back(Builder.getInt32(2));
4331   if (NumElementsDst == 4)
4332     Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
4333   llvm::Constant *Mask = llvm::ConstantVector::get(Args);
4334   return Builder.CreateShuffleVector(Src, UnV, Mask);
4335 }
4336 
4337 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
4338 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
4339 // but could be scalar or vectors of different lengths, and either can be
4340 // pointer.
4341 // There are 4 cases:
4342 // 1. non-pointer -> non-pointer  : needs 1 bitcast
4343 // 2. pointer -> pointer          : needs 1 bitcast or addrspacecast
4344 // 3. pointer -> non-pointer
4345 //   a) pointer -> intptr_t       : needs 1 ptrtoint
4346 //   b) pointer -> non-intptr_t   : needs 1 ptrtoint then 1 bitcast
4347 // 4. non-pointer -> pointer
4348 //   a) intptr_t -> pointer       : needs 1 inttoptr
4349 //   b) non-intptr_t -> pointer   : needs 1 bitcast then 1 inttoptr
4350 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
4351 // allow casting directly between pointer types and non-integer non-pointer
4352 // types.
4353 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4354                                            const llvm::DataLayout &DL,
4355                                            Value *Src, llvm::Type *DstTy,
4356                                            StringRef Name = "") {
4357   auto SrcTy = Src->getType();
4358 
4359   // Case 1.
4360   if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4361     return Builder.CreateBitCast(Src, DstTy, Name);
4362 
4363   // Case 2.
4364   if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4365     return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4366 
4367   // Case 3.
4368   if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4369     // Case 3b.
4370     if (!DstTy->isIntegerTy())
4371       Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4372     // Cases 3a and 3b.
4373     return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4374   }
4375 
4376   // Case 4b.
4377   if (!SrcTy->isIntegerTy())
4378     Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4379   // Cases 4a and 4b.
4380   return Builder.CreateIntToPtr(Src, DstTy, Name);
4381 }
4382 
4383 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4384   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
4385   llvm::Type *DstTy = ConvertType(E->getType());
4386 
4387   llvm::Type *SrcTy = Src->getType();
4388   unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4389     cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4390   unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4391     cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
4392 
4393   // Going from vec3 to non-vec3 is a special case and requires a shuffle
4394   // vector to get a vec4, then a bitcast if the target type is different.
4395   if (NumElementsSrc == 3 && NumElementsDst != 3) {
4396     Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4397 
4398     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4399       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4400                                          DstTy);
4401     }
4402 
4403     Src->setName("astype");
4404     return Src;
4405   }
4406 
4407   // Going from non-vec3 to vec3 is a special case and requires a bitcast
4408   // to vec4 if the original type is not vec4, then a shuffle vector to
4409   // get a vec3.
4410   if (NumElementsSrc != 3 && NumElementsDst == 3) {
4411     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4412       auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
4413       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4414                                          Vec4Ty);
4415     }
4416 
4417     Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4418     Src->setName("astype");
4419     return Src;
4420   }
4421 
4422   return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4423                                       Src, DstTy, "astype");
4424 }
4425 
4426 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4427   return CGF.EmitAtomicExpr(E).getScalarVal();
4428 }
4429 
4430 //===----------------------------------------------------------------------===//
4431 //                         Entry Point into this File
4432 //===----------------------------------------------------------------------===//
4433 
4434 /// Emit the computation of the specified expression of scalar type, ignoring
4435 /// the result.
4436 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4437   assert(E && hasScalarEvaluationKind(E->getType()) &&
4438          "Invalid scalar expression to emit");
4439 
4440   return ScalarExprEmitter(*this, IgnoreResultAssign)
4441       .Visit(const_cast<Expr *>(E));
4442 }
4443 
4444 /// Emit a conversion from the specified type to the specified destination type,
4445 /// both of which are LLVM scalar types.
4446 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4447                                              QualType DstTy,
4448                                              SourceLocation Loc) {
4449   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4450          "Invalid scalar expression to emit");
4451   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4452 }
4453 
4454 /// Emit a conversion from the specified complex type to the specified
4455 /// destination type, where the destination type is an LLVM scalar type.
4456 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4457                                                       QualType SrcTy,
4458                                                       QualType DstTy,
4459                                                       SourceLocation Loc) {
4460   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4461          "Invalid complex -> scalar conversion");
4462   return ScalarExprEmitter(*this)
4463       .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4464 }
4465 
4466 
4467 llvm::Value *CodeGenFunction::
4468 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4469                         bool isInc, bool isPre) {
4470   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4471 }
4472 
4473 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4474   // object->isa or (*object).isa
4475   // Generate code as for: *(Class*)object
4476 
4477   Expr *BaseExpr = E->getBase();
4478   Address Addr = Address::invalid();
4479   if (BaseExpr->isRValue()) {
4480     Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4481   } else {
4482     Addr = EmitLValue(BaseExpr).getAddress();
4483   }
4484 
4485   // Cast the address to Class*.
4486   Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4487   return MakeAddrLValue(Addr, E->getType());
4488 }
4489 
4490 
4491 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4492                                             const CompoundAssignOperator *E) {
4493   ScalarExprEmitter Scalar(*this);
4494   Value *Result = nullptr;
4495   switch (E->getOpcode()) {
4496 #define COMPOUND_OP(Op)                                                       \
4497     case BO_##Op##Assign:                                                     \
4498       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4499                                              Result)
4500   COMPOUND_OP(Mul);
4501   COMPOUND_OP(Div);
4502   COMPOUND_OP(Rem);
4503   COMPOUND_OP(Add);
4504   COMPOUND_OP(Sub);
4505   COMPOUND_OP(Shl);
4506   COMPOUND_OP(Shr);
4507   COMPOUND_OP(And);
4508   COMPOUND_OP(Xor);
4509   COMPOUND_OP(Or);
4510 #undef COMPOUND_OP
4511 
4512   case BO_PtrMemD:
4513   case BO_PtrMemI:
4514   case BO_Mul:
4515   case BO_Div:
4516   case BO_Rem:
4517   case BO_Add:
4518   case BO_Sub:
4519   case BO_Shl:
4520   case BO_Shr:
4521   case BO_LT:
4522   case BO_GT:
4523   case BO_LE:
4524   case BO_GE:
4525   case BO_EQ:
4526   case BO_NE:
4527   case BO_Cmp:
4528   case BO_And:
4529   case BO_Xor:
4530   case BO_Or:
4531   case BO_LAnd:
4532   case BO_LOr:
4533   case BO_Assign:
4534   case BO_Comma:
4535     llvm_unreachable("Not valid compound assignment operators");
4536   }
4537 
4538   llvm_unreachable("Unhandled compound assignment operator");
4539 }
4540 
4541 struct GEPOffsetAndOverflow {
4542   // The total (signed) byte offset for the GEP.
4543   llvm::Value *TotalOffset;
4544   // The offset overflow flag - true if the total offset overflows.
4545   llvm::Value *OffsetOverflows;
4546 };
4547 
4548 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
4549 /// and compute the total offset it applies from it's base pointer BasePtr.
4550 /// Returns offset in bytes and a boolean flag whether an overflow happened
4551 /// during evaluation.
4552 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4553                                                  llvm::LLVMContext &VMContext,
4554                                                  CodeGenModule &CGM,
4555                                                  CGBuilderTy Builder) {
4556   const auto &DL = CGM.getDataLayout();
4557 
4558   // The total (signed) byte offset for the GEP.
4559   llvm::Value *TotalOffset = nullptr;
4560 
4561   // Was the GEP already reduced to a constant?
4562   if (isa<llvm::Constant>(GEPVal)) {
4563     // Compute the offset by casting both pointers to integers and subtracting:
4564     // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4565     Value *BasePtr_int =
4566         Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4567     Value *GEPVal_int =
4568         Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4569     TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4570     return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4571   }
4572 
4573   auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4574   assert(GEP->getPointerOperand() == BasePtr &&
4575          "BasePtr must be the the base of the GEP.");
4576   assert(GEP->isInBounds() && "Expected inbounds GEP");
4577 
4578   auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4579 
4580   // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4581   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4582   auto *SAddIntrinsic =
4583       CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4584   auto *SMulIntrinsic =
4585       CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4586 
4587   // The offset overflow flag - true if the total offset overflows.
4588   llvm::Value *OffsetOverflows = Builder.getFalse();
4589 
4590   /// Return the result of the given binary operation.
4591   auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4592                   llvm::Value *RHS) -> llvm::Value * {
4593     assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
4594 
4595     // If the operands are constants, return a constant result.
4596     if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4597       if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4598         llvm::APInt N;
4599         bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4600                                                   /*Signed=*/true, N);
4601         if (HasOverflow)
4602           OffsetOverflows = Builder.getTrue();
4603         return llvm::ConstantInt::get(VMContext, N);
4604       }
4605     }
4606 
4607     // Otherwise, compute the result with checked arithmetic.
4608     auto *ResultAndOverflow = Builder.CreateCall(
4609         (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4610     OffsetOverflows = Builder.CreateOr(
4611         Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
4612     return Builder.CreateExtractValue(ResultAndOverflow, 0);
4613   };
4614 
4615   // Determine the total byte offset by looking at each GEP operand.
4616   for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4617        GTI != GTE; ++GTI) {
4618     llvm::Value *LocalOffset;
4619     auto *Index = GTI.getOperand();
4620     // Compute the local offset contributed by this indexing step:
4621     if (auto *STy = GTI.getStructTypeOrNull()) {
4622       // For struct indexing, the local offset is the byte position of the
4623       // specified field.
4624       unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4625       LocalOffset = llvm::ConstantInt::get(
4626           IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4627     } else {
4628       // Otherwise this is array-like indexing. The local offset is the index
4629       // multiplied by the element size.
4630       auto *ElementSize = llvm::ConstantInt::get(
4631           IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4632       auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4633       LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4634     }
4635 
4636     // If this is the first offset, set it as the total offset. Otherwise, add
4637     // the local offset into the running total.
4638     if (!TotalOffset || TotalOffset == Zero)
4639       TotalOffset = LocalOffset;
4640     else
4641       TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4642   }
4643 
4644   return {TotalOffset, OffsetOverflows};
4645 }
4646 
4647 Value *
4648 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4649                                         bool SignedIndices, bool IsSubtraction,
4650                                         SourceLocation Loc, const Twine &Name) {
4651   Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4652 
4653   // If the pointer overflow sanitizer isn't enabled, do nothing.
4654   if (!SanOpts.has(SanitizerKind::PointerOverflow))
4655     return GEPVal;
4656 
4657   llvm::Type *PtrTy = Ptr->getType();
4658 
4659   // Perform nullptr-and-offset check unless the nullptr is defined.
4660   bool PerformNullCheck = !NullPointerIsDefined(
4661       Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4662   // Check for overflows unless the GEP got constant-folded,
4663   // and only in the default address space
4664   bool PerformOverflowCheck =
4665       !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4666 
4667   if (!(PerformNullCheck || PerformOverflowCheck))
4668     return GEPVal;
4669 
4670   const auto &DL = CGM.getDataLayout();
4671 
4672   SanitizerScope SanScope(this);
4673   llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4674 
4675   GEPOffsetAndOverflow EvaluatedGEP =
4676       EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4677 
4678   assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4679           EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4680          "If the offset got constant-folded, we don't expect that there was an "
4681          "overflow.");
4682 
4683   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4684 
4685   // Common case: if the total offset is zero, and we are using C++ semantics,
4686   // where nullptr+0 is defined, don't emit a check.
4687   if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
4688     return GEPVal;
4689 
4690   // Now that we've computed the total offset, add it to the base pointer (with
4691   // wrapping semantics).
4692   auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
4693   auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
4694 
4695   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
4696 
4697   if (PerformNullCheck) {
4698     // In C++, if the base pointer evaluates to a null pointer value,
4699     // the only valid  pointer this inbounds GEP can produce is also
4700     // a null pointer, so the offset must also evaluate to zero.
4701     // Likewise, if we have non-zero base pointer, we can not get null pointer
4702     // as a result, so the offset can not be -intptr_t(BasePtr).
4703     // In other words, both pointers are either null, or both are non-null,
4704     // or the behaviour is undefined.
4705     //
4706     // C, however, is more strict in this regard, and gives more
4707     // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4708     // So both the input to the 'gep inbounds' AND the output must not be null.
4709     auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4710     auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4711     auto *Valid =
4712         CGM.getLangOpts().CPlusPlus
4713             ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4714             : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4715     Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
4716   }
4717 
4718   if (PerformOverflowCheck) {
4719     // The GEP is valid if:
4720     // 1) The total offset doesn't overflow, and
4721     // 2) The sign of the difference between the computed address and the base
4722     // pointer matches the sign of the total offset.
4723     llvm::Value *ValidGEP;
4724     auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
4725     if (SignedIndices) {
4726       // GEP is computed as `unsigned base + signed offset`, therefore:
4727       // * If offset was positive, then the computed pointer can not be
4728       //   [unsigned] less than the base pointer, unless it overflowed.
4729       // * If offset was negative, then the computed pointer can not be
4730       //   [unsigned] greater than the bas pointere, unless it overflowed.
4731       auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4732       auto *PosOrZeroOffset =
4733           Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
4734       llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4735       ValidGEP =
4736           Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
4737     } else if (!IsSubtraction) {
4738       // GEP is computed as `unsigned base + unsigned offset`,  therefore the
4739       // computed pointer can not be [unsigned] less than base pointer,
4740       // unless there was an overflow.
4741       // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
4742       ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4743     } else {
4744       // GEP is computed as `unsigned base - unsigned offset`, therefore the
4745       // computed pointer can not be [unsigned] greater than base pointer,
4746       // unless there was an overflow.
4747       // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
4748       ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4749     }
4750     ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
4751     Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
4752   }
4753 
4754   assert(!Checks.empty() && "Should have produced some checks.");
4755 
4756   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4757   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4758   llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4759   EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
4760 
4761   return GEPVal;
4762 }
4763