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