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