1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCleanup.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "CodeGenModule.h" 20 #include "TargetInfo.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/Basic/TargetInfo.h" 27 #include "clang/Frontend/CodeGenOptions.h" 28 #include "llvm/ADT/Optional.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/Module.h" 36 #include <cstdarg> 37 38 using namespace clang; 39 using namespace CodeGen; 40 using llvm::Value; 41 42 //===----------------------------------------------------------------------===// 43 // Scalar Expression Emitter 44 //===----------------------------------------------------------------------===// 45 46 namespace { 47 struct BinOpInfo { 48 Value *LHS; 49 Value *RHS; 50 QualType Ty; // Computation Type. 51 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform 52 bool FPContractable; 53 const Expr *E; // Entire expr, for error unsupported. May not be binop. 54 }; 55 56 static bool MustVisitNullValue(const Expr *E) { 57 // If a null pointer expression's type is the C++0x nullptr_t, then 58 // it's not necessarily a simple constant and it must be evaluated 59 // for its potential side effects. 60 return E->getType()->isNullPtrType(); 61 } 62 63 /// If \p E is a widened promoted integer, get its base (unpromoted) type. 64 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx, 65 const Expr *E) { 66 const Expr *Base = E->IgnoreImpCasts(); 67 if (E == Base) 68 return llvm::None; 69 70 QualType BaseTy = Base->getType(); 71 if (!BaseTy->isPromotableIntegerType() || 72 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType())) 73 return llvm::None; 74 75 return BaseTy; 76 } 77 78 /// Check if \p E is a widened promoted integer. 79 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) { 80 return getUnwidenedIntegerType(Ctx, E).hasValue(); 81 } 82 83 /// Check if we can skip the overflow check for \p Op. 84 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) { 85 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) && 86 "Expected a unary or binary operator"); 87 88 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E)) 89 return IsWidenedIntegerOp(Ctx, UO->getSubExpr()); 90 91 const auto *BO = cast<BinaryOperator>(Op.E); 92 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS()); 93 if (!OptionalLHSTy) 94 return false; 95 96 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS()); 97 if (!OptionalRHSTy) 98 return false; 99 100 QualType LHSTy = *OptionalLHSTy; 101 QualType RHSTy = *OptionalRHSTy; 102 103 // We usually don't need overflow checks for binary operations with widened 104 // operands. Multiplication with promoted unsigned operands is a special case. 105 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) || 106 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType()) 107 return true; 108 109 // The overflow check can be skipped if either one of the unpromoted types 110 // are less than half the size of the promoted type. 111 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType()); 112 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize || 113 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize; 114 } 115 116 class ScalarExprEmitter 117 : public StmtVisitor<ScalarExprEmitter, Value*> { 118 CodeGenFunction &CGF; 119 CGBuilderTy &Builder; 120 bool IgnoreResultAssign; 121 llvm::LLVMContext &VMContext; 122 public: 123 124 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 125 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 126 VMContext(cgf.getLLVMContext()) { 127 } 128 129 //===--------------------------------------------------------------------===// 130 // Utilities 131 //===--------------------------------------------------------------------===// 132 133 bool TestAndClearIgnoreResultAssign() { 134 bool I = IgnoreResultAssign; 135 IgnoreResultAssign = false; 136 return I; 137 } 138 139 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 140 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 141 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) { 142 return CGF.EmitCheckedLValue(E, TCK); 143 } 144 145 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks, 146 const BinOpInfo &Info); 147 148 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 149 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal(); 150 } 151 152 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) { 153 const AlignValueAttr *AVAttr = nullptr; 154 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 155 const ValueDecl *VD = DRE->getDecl(); 156 157 if (VD->getType()->isReferenceType()) { 158 if (const auto *TTy = 159 dyn_cast<TypedefType>(VD->getType().getNonReferenceType())) 160 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 161 } else { 162 // Assumptions for function parameters are emitted at the start of the 163 // function, so there is no need to repeat that here. 164 if (isa<ParmVarDecl>(VD)) 165 return; 166 167 AVAttr = VD->getAttr<AlignValueAttr>(); 168 } 169 } 170 171 if (!AVAttr) 172 if (const auto *TTy = 173 dyn_cast<TypedefType>(E->getType())) 174 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>(); 175 176 if (!AVAttr) 177 return; 178 179 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment()); 180 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue); 181 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue()); 182 } 183 184 /// EmitLoadOfLValue - Given an expression with complex type that represents a 185 /// value l-value, this method emits the address of the l-value, then loads 186 /// and returns the result. 187 Value *EmitLoadOfLValue(const Expr *E) { 188 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load), 189 E->getExprLoc()); 190 191 EmitLValueAlignmentAssumption(E, V); 192 return V; 193 } 194 195 /// EmitConversionToBool - Convert the specified expression value to a 196 /// boolean (i1) truth value. This is equivalent to "Val != 0". 197 Value *EmitConversionToBool(Value *Src, QualType DstTy); 198 199 /// Emit a check that a conversion to or from a floating-point type does not 200 /// overflow. 201 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType, 202 Value *Src, QualType SrcType, QualType DstType, 203 llvm::Type *DstTy, SourceLocation Loc); 204 205 /// Emit a conversion from the specified type to the specified destination 206 /// type, both of which are LLVM scalar types. 207 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, 208 SourceLocation Loc); 209 210 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, 211 SourceLocation Loc, bool TreatBooleanAsSigned); 212 213 /// Emit a conversion from the specified complex type to the specified 214 /// destination type, where the destination type is an LLVM scalar type. 215 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 216 QualType SrcTy, QualType DstTy, 217 SourceLocation Loc); 218 219 /// EmitNullValue - Emit a value that corresponds to null for the given type. 220 Value *EmitNullValue(QualType Ty); 221 222 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion. 223 Value *EmitFloatToBoolConversion(Value *V) { 224 // Compare against 0.0 for fp scalars. 225 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType()); 226 return Builder.CreateFCmpUNE(V, Zero, "tobool"); 227 } 228 229 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion. 230 Value *EmitPointerToBoolConversion(Value *V, QualType QT) { 231 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT); 232 233 return Builder.CreateICmpNE(V, Zero, "tobool"); 234 } 235 236 Value *EmitIntToBoolConversion(Value *V) { 237 // Because of the type rules of C, we often end up computing a 238 // logical value, then zero extending it to int, then wanting it 239 // as a logical value again. Optimize this common case. 240 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) { 241 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) { 242 Value *Result = ZI->getOperand(0); 243 // If there aren't any more uses, zap the instruction to save space. 244 // Note that there can be more uses, for example if this 245 // is the result of an assignment. 246 if (ZI->use_empty()) 247 ZI->eraseFromParent(); 248 return Result; 249 } 250 } 251 252 return Builder.CreateIsNotNull(V, "tobool"); 253 } 254 255 //===--------------------------------------------------------------------===// 256 // Visitor Methods 257 //===--------------------------------------------------------------------===// 258 259 Value *Visit(Expr *E) { 260 ApplyDebugLocation DL(CGF, E); 261 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E); 262 } 263 264 Value *VisitStmt(Stmt *S) { 265 S->dump(CGF.getContext().getSourceManager()); 266 llvm_unreachable("Stmt can't have complex result type!"); 267 } 268 Value *VisitExpr(Expr *S); 269 270 Value *VisitParenExpr(ParenExpr *PE) { 271 return Visit(PE->getSubExpr()); 272 } 273 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 274 return Visit(E->getReplacement()); 275 } 276 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 277 return Visit(GE->getResultExpr()); 278 } 279 280 // Leaves. 281 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 282 return Builder.getInt(E->getValue()); 283 } 284 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 285 return llvm::ConstantFP::get(VMContext, E->getValue()); 286 } 287 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 288 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 289 } 290 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 291 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 292 } 293 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 294 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 295 } 296 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 297 return EmitNullValue(E->getType()); 298 } 299 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 300 return EmitNullValue(E->getType()); 301 } 302 Value *VisitOffsetOfExpr(OffsetOfExpr *E); 303 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 304 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 305 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel()); 306 return Builder.CreateBitCast(V, ConvertType(E->getType())); 307 } 308 309 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) { 310 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength()); 311 } 312 313 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) { 314 return CGF.EmitPseudoObjectRValue(E).getScalarVal(); 315 } 316 317 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) { 318 if (E->isGLValue()) 319 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc()); 320 321 // Otherwise, assume the mapping is the scalar directly. 322 return CGF.getOpaqueRValueMapping(E).getScalarVal(); 323 } 324 325 // l-values. 326 Value *VisitDeclRefExpr(DeclRefExpr *E) { 327 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) { 328 if (result.isReference()) 329 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E), 330 E->getExprLoc()); 331 return result.getValue(); 332 } 333 return EmitLoadOfLValue(E); 334 } 335 336 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 337 return CGF.EmitObjCSelectorExpr(E); 338 } 339 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 340 return CGF.EmitObjCProtocolExpr(E); 341 } 342 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 343 return EmitLoadOfLValue(E); 344 } 345 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 346 if (E->getMethodDecl() && 347 E->getMethodDecl()->getReturnType()->isReferenceType()) 348 return EmitLoadOfLValue(E); 349 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 350 } 351 352 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) { 353 LValue LV = CGF.EmitObjCIsaExpr(E); 354 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal(); 355 return V; 356 } 357 358 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { 359 VersionTuple Version = E->getVersion(); 360 361 // If we're checking for a platform older than our minimum deployment 362 // target, we can fold the check away. 363 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion()) 364 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1); 365 366 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor(); 367 llvm::Value *Args[] = { 368 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()), 369 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0), 370 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0), 371 }; 372 373 return CGF.EmitBuiltinAvailable(Args); 374 } 375 376 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 377 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 378 Value *VisitConvertVectorExpr(ConvertVectorExpr *E); 379 Value *VisitMemberExpr(MemberExpr *E); 380 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 381 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 382 return EmitLoadOfLValue(E); 383 } 384 385 Value *VisitInitListExpr(InitListExpr *E); 386 387 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 388 assert(CGF.getArrayInitIndex() && 389 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?"); 390 return CGF.getArrayInitIndex(); 391 } 392 393 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 394 return EmitNullValue(E->getType()); 395 } 396 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) { 397 CGF.CGM.EmitExplicitCastExprType(E, &CGF); 398 return VisitCastExpr(E); 399 } 400 Value *VisitCastExpr(CastExpr *E); 401 402 Value *VisitCallExpr(const CallExpr *E) { 403 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) 404 return EmitLoadOfLValue(E); 405 406 Value *V = CGF.EmitCallExpr(E).getScalarVal(); 407 408 EmitLValueAlignmentAssumption(E, V); 409 return V; 410 } 411 412 Value *VisitStmtExpr(const StmtExpr *E); 413 414 // Unary Operators. 415 Value *VisitUnaryPostDec(const UnaryOperator *E) { 416 LValue LV = EmitLValue(E->getSubExpr()); 417 return EmitScalarPrePostIncDec(E, LV, false, false); 418 } 419 Value *VisitUnaryPostInc(const UnaryOperator *E) { 420 LValue LV = EmitLValue(E->getSubExpr()); 421 return EmitScalarPrePostIncDec(E, LV, true, false); 422 } 423 Value *VisitUnaryPreDec(const UnaryOperator *E) { 424 LValue LV = EmitLValue(E->getSubExpr()); 425 return EmitScalarPrePostIncDec(E, LV, false, true); 426 } 427 Value *VisitUnaryPreInc(const UnaryOperator *E) { 428 LValue LV = EmitLValue(E->getSubExpr()); 429 return EmitScalarPrePostIncDec(E, LV, true, true); 430 } 431 432 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E, 433 llvm::Value *InVal, 434 bool IsInc); 435 436 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 437 bool isInc, bool isPre); 438 439 440 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 441 if (isa<MemberPointerType>(E->getType())) // never sugared 442 return CGF.CGM.getMemberPointerConstant(E); 443 444 return EmitLValue(E->getSubExpr()).getPointer(); 445 } 446 Value *VisitUnaryDeref(const UnaryOperator *E) { 447 if (E->getType()->isVoidType()) 448 return Visit(E->getSubExpr()); // the actual value should be unused 449 return EmitLoadOfLValue(E); 450 } 451 Value *VisitUnaryPlus(const UnaryOperator *E) { 452 // This differs from gcc, though, most likely due to a bug in gcc. 453 TestAndClearIgnoreResultAssign(); 454 return Visit(E->getSubExpr()); 455 } 456 Value *VisitUnaryMinus (const UnaryOperator *E); 457 Value *VisitUnaryNot (const UnaryOperator *E); 458 Value *VisitUnaryLNot (const UnaryOperator *E); 459 Value *VisitUnaryReal (const UnaryOperator *E); 460 Value *VisitUnaryImag (const UnaryOperator *E); 461 Value *VisitUnaryExtension(const UnaryOperator *E) { 462 return Visit(E->getSubExpr()); 463 } 464 465 // C++ 466 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) { 467 return EmitLoadOfLValue(E); 468 } 469 470 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 471 return Visit(DAE->getExpr()); 472 } 473 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 474 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF); 475 return Visit(DIE->getExpr()); 476 } 477 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 478 return CGF.LoadCXXThis(); 479 } 480 481 Value *VisitExprWithCleanups(ExprWithCleanups *E); 482 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 483 return CGF.EmitCXXNewExpr(E); 484 } 485 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 486 CGF.EmitCXXDeleteExpr(E); 487 return nullptr; 488 } 489 490 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) { 491 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 492 } 493 494 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 495 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue()); 496 } 497 498 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 499 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue()); 500 } 501 502 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 503 // C++ [expr.pseudo]p1: 504 // The result shall only be used as the operand for the function call 505 // operator (), and the result of such a call has type void. The only 506 // effect is the evaluation of the postfix-expression before the dot or 507 // arrow. 508 CGF.EmitScalarExpr(E->getBase()); 509 return nullptr; 510 } 511 512 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 513 return EmitNullValue(E->getType()); 514 } 515 516 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) { 517 CGF.EmitCXXThrowExpr(E); 518 return nullptr; 519 } 520 521 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 522 return Builder.getInt1(E->getValue()); 523 } 524 525 // Binary Operators. 526 Value *EmitMul(const BinOpInfo &Ops) { 527 if (Ops.Ty->isSignedIntegerOrEnumerationType()) { 528 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 529 case LangOptions::SOB_Defined: 530 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 531 case LangOptions::SOB_Undefined: 532 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 533 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 534 // Fall through. 535 case LangOptions::SOB_Trapping: 536 if (CanElideOverflowCheck(CGF.getContext(), Ops)) 537 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul"); 538 return EmitOverflowCheckedBinOp(Ops); 539 } 540 } 541 542 if (Ops.Ty->isUnsignedIntegerType() && 543 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 544 !CanElideOverflowCheck(CGF.getContext(), Ops)) 545 return EmitOverflowCheckedBinOp(Ops); 546 547 if (Ops.LHS->getType()->isFPOrFPVectorTy()) 548 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 549 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 550 } 551 /// Create a binary op that checks for overflow. 552 /// Currently only supports +, - and *. 553 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 554 555 // Check for undefined division and modulus behaviors. 556 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops, 557 llvm::Value *Zero,bool isDiv); 558 // Common helper for getting how wide LHS of shift is. 559 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS); 560 Value *EmitDiv(const BinOpInfo &Ops); 561 Value *EmitRem(const BinOpInfo &Ops); 562 Value *EmitAdd(const BinOpInfo &Ops); 563 Value *EmitSub(const BinOpInfo &Ops); 564 Value *EmitShl(const BinOpInfo &Ops); 565 Value *EmitShr(const BinOpInfo &Ops); 566 Value *EmitAnd(const BinOpInfo &Ops) { 567 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 568 } 569 Value *EmitXor(const BinOpInfo &Ops) { 570 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 571 } 572 Value *EmitOr (const BinOpInfo &Ops) { 573 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 574 } 575 576 BinOpInfo EmitBinOps(const BinaryOperator *E); 577 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E, 578 Value *(ScalarExprEmitter::*F)(const BinOpInfo &), 579 Value *&Result); 580 581 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 582 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 583 584 // Binary operators and binary compound assignment operators. 585 #define HANDLEBINOP(OP) \ 586 Value *VisitBin ## OP(const BinaryOperator *E) { \ 587 return Emit ## OP(EmitBinOps(E)); \ 588 } \ 589 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 590 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 591 } 592 HANDLEBINOP(Mul) 593 HANDLEBINOP(Div) 594 HANDLEBINOP(Rem) 595 HANDLEBINOP(Add) 596 HANDLEBINOP(Sub) 597 HANDLEBINOP(Shl) 598 HANDLEBINOP(Shr) 599 HANDLEBINOP(And) 600 HANDLEBINOP(Xor) 601 HANDLEBINOP(Or) 602 #undef HANDLEBINOP 603 604 // Comparisons. 605 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc, 606 llvm::CmpInst::Predicate SICmpOpc, 607 llvm::CmpInst::Predicate FCmpOpc); 608 #define VISITCOMP(CODE, UI, SI, FP) \ 609 Value *VisitBin##CODE(const BinaryOperator *E) { \ 610 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 611 llvm::FCmpInst::FP); } 612 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT) 613 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT) 614 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE) 615 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE) 616 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ) 617 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE) 618 #undef VISITCOMP 619 620 Value *VisitBinAssign (const BinaryOperator *E); 621 622 Value *VisitBinLAnd (const BinaryOperator *E); 623 Value *VisitBinLOr (const BinaryOperator *E); 624 Value *VisitBinComma (const BinaryOperator *E); 625 626 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); } 627 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); } 628 629 // Other Operators. 630 Value *VisitBlockExpr(const BlockExpr *BE); 631 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *); 632 Value *VisitChooseExpr(ChooseExpr *CE); 633 Value *VisitVAArgExpr(VAArgExpr *VE); 634 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 635 return CGF.EmitObjCStringLiteral(E); 636 } 637 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) { 638 return CGF.EmitObjCBoxedExpr(E); 639 } 640 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) { 641 return CGF.EmitObjCArrayLiteral(E); 642 } 643 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { 644 return CGF.EmitObjCDictionaryLiteral(E); 645 } 646 Value *VisitAsTypeExpr(AsTypeExpr *CE); 647 Value *VisitAtomicExpr(AtomicExpr *AE); 648 }; 649 } // end anonymous namespace. 650 651 //===----------------------------------------------------------------------===// 652 // Utilities 653 //===----------------------------------------------------------------------===// 654 655 /// EmitConversionToBool - Convert the specified expression value to a 656 /// boolean (i1) truth value. This is equivalent to "Val != 0". 657 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 658 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs"); 659 660 if (SrcType->isRealFloatingType()) 661 return EmitFloatToBoolConversion(Src); 662 663 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType)) 664 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT); 665 666 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 667 "Unknown scalar type to convert"); 668 669 if (isa<llvm::IntegerType>(Src->getType())) 670 return EmitIntToBoolConversion(Src); 671 672 assert(isa<llvm::PointerType>(Src->getType())); 673 return EmitPointerToBoolConversion(Src, SrcType); 674 } 675 676 void ScalarExprEmitter::EmitFloatConversionCheck( 677 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType, 678 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) { 679 CodeGenFunction::SanitizerScope SanScope(&CGF); 680 using llvm::APFloat; 681 using llvm::APSInt; 682 683 llvm::Type *SrcTy = Src->getType(); 684 685 llvm::Value *Check = nullptr; 686 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) { 687 // Integer to floating-point. This can fail for unsigned short -> __half 688 // or unsigned __int128 -> float. 689 assert(DstType->isFloatingType()); 690 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType(); 691 692 APFloat LargestFloat = 693 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType)); 694 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned); 695 696 bool IsExact; 697 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero, 698 &IsExact) != APFloat::opOK) 699 // The range of representable values of this floating point type includes 700 // all values of this integer type. Don't need an overflow check. 701 return; 702 703 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt); 704 if (SrcIsUnsigned) 705 Check = Builder.CreateICmpULE(Src, Max); 706 else { 707 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt); 708 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min); 709 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max); 710 Check = Builder.CreateAnd(GE, LE); 711 } 712 } else { 713 const llvm::fltSemantics &SrcSema = 714 CGF.getContext().getFloatTypeSemantics(OrigSrcType); 715 if (isa<llvm::IntegerType>(DstTy)) { 716 // Floating-point to integer. This has undefined behavior if the source is 717 // +-Inf, NaN, or doesn't fit into the destination type (after truncation 718 // to an integer). 719 unsigned Width = CGF.getContext().getIntWidth(DstType); 720 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType(); 721 722 APSInt Min = APSInt::getMinValue(Width, Unsigned); 723 APFloat MinSrc(SrcSema, APFloat::uninitialized); 724 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) & 725 APFloat::opOverflow) 726 // Don't need an overflow check for lower bound. Just check for 727 // -Inf/NaN. 728 MinSrc = APFloat::getInf(SrcSema, true); 729 else 730 // Find the largest value which is too small to represent (before 731 // truncation toward zero). 732 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative); 733 734 APSInt Max = APSInt::getMaxValue(Width, Unsigned); 735 APFloat MaxSrc(SrcSema, APFloat::uninitialized); 736 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) & 737 APFloat::opOverflow) 738 // Don't need an overflow check for upper bound. Just check for 739 // +Inf/NaN. 740 MaxSrc = APFloat::getInf(SrcSema, false); 741 else 742 // Find the smallest value which is too large to represent (before 743 // truncation toward zero). 744 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive); 745 746 // If we're converting from __half, convert the range to float to match 747 // the type of src. 748 if (OrigSrcType->isHalfType()) { 749 const llvm::fltSemantics &Sema = 750 CGF.getContext().getFloatTypeSemantics(SrcType); 751 bool IsInexact; 752 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 753 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact); 754 } 755 756 llvm::Value *GE = 757 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc)); 758 llvm::Value *LE = 759 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc)); 760 Check = Builder.CreateAnd(GE, LE); 761 } else { 762 // FIXME: Maybe split this sanitizer out from float-cast-overflow. 763 // 764 // Floating-point to floating-point. This has undefined behavior if the 765 // source is not in the range of representable values of the destination 766 // type. The C and C++ standards are spectacularly unclear here. We 767 // diagnose finite out-of-range conversions, but allow infinities and NaNs 768 // to convert to the corresponding value in the smaller type. 769 // 770 // C11 Annex F gives all such conversions defined behavior for IEC 60559 771 // conforming implementations. Unfortunately, LLVM's fptrunc instruction 772 // does not. 773 774 // Converting from a lower rank to a higher rank can never have 775 // undefined behavior, since higher-rank types must have a superset 776 // of values of lower-rank types. 777 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1) 778 return; 779 780 assert(!OrigSrcType->isHalfType() && 781 "should not check conversion from __half, it has the lowest rank"); 782 783 const llvm::fltSemantics &DstSema = 784 CGF.getContext().getFloatTypeSemantics(DstType); 785 APFloat MinBad = APFloat::getLargest(DstSema, false); 786 APFloat MaxBad = APFloat::getInf(DstSema, false); 787 788 bool IsInexact; 789 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact); 790 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact); 791 792 Value *AbsSrc = CGF.EmitNounwindRuntimeCall( 793 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src); 794 llvm::Value *GE = 795 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad)); 796 llvm::Value *LE = 797 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad)); 798 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE)); 799 } 800 } 801 802 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc), 803 CGF.EmitCheckTypeDescriptor(OrigSrcType), 804 CGF.EmitCheckTypeDescriptor(DstType)}; 805 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow), 806 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc); 807 } 808 809 /// Emit a conversion from the specified type to the specified destination type, 810 /// both of which are LLVM scalar types. 811 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 812 QualType DstType, 813 SourceLocation Loc) { 814 return EmitScalarConversion(Src, SrcType, DstType, Loc, false); 815 } 816 817 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 818 QualType DstType, 819 SourceLocation Loc, 820 bool TreatBooleanAsSigned) { 821 SrcType = CGF.getContext().getCanonicalType(SrcType); 822 DstType = CGF.getContext().getCanonicalType(DstType); 823 if (SrcType == DstType) return Src; 824 825 if (DstType->isVoidType()) return nullptr; 826 827 llvm::Value *OrigSrc = Src; 828 QualType OrigSrcType = SrcType; 829 llvm::Type *SrcTy = Src->getType(); 830 831 // Handle conversions to bool first, they are special: comparisons against 0. 832 if (DstType->isBooleanType()) 833 return EmitConversionToBool(Src, SrcType); 834 835 llvm::Type *DstTy = ConvertType(DstType); 836 837 // Cast from half through float if half isn't a native type. 838 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 839 // Cast to FP using the intrinsic if the half type itself isn't supported. 840 if (DstTy->isFloatingPointTy()) { 841 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) 842 return Builder.CreateCall( 843 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy), 844 Src); 845 } else { 846 // Cast to other types through float, using either the intrinsic or FPExt, 847 // depending on whether the half type itself is supported 848 // (as opposed to operations on half, available with NativeHalfType). 849 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 850 Src = Builder.CreateCall( 851 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 852 CGF.CGM.FloatTy), 853 Src); 854 } else { 855 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv"); 856 } 857 SrcType = CGF.getContext().FloatTy; 858 SrcTy = CGF.FloatTy; 859 } 860 } 861 862 // Ignore conversions like int -> uint. 863 if (SrcTy == DstTy) 864 return Src; 865 866 // Handle pointer conversions next: pointers can only be converted to/from 867 // other pointers and integers. Check for pointer types in terms of LLVM, as 868 // some native types (like Obj-C id) may map to a pointer type. 869 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) { 870 // The source value may be an integer, or a pointer. 871 if (isa<llvm::PointerType>(SrcTy)) 872 return Builder.CreateBitCast(Src, DstTy, "conv"); 873 874 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 875 // First, convert to the correct width so that we control the kind of 876 // extension. 877 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT); 878 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 879 llvm::Value* IntResult = 880 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 881 // Then, cast to pointer. 882 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 883 } 884 885 if (isa<llvm::PointerType>(SrcTy)) { 886 // Must be an ptr to int cast. 887 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 888 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 889 } 890 891 // A scalar can be splatted to an extended vector of the same element type 892 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 893 // Sema should add casts to make sure that the source expression's type is 894 // the same as the vector's element type (sans qualifiers) 895 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() == 896 SrcType.getTypePtr() && 897 "Splatted expr doesn't match with vector element type?"); 898 899 // Splat the element across to all elements 900 unsigned NumElements = DstTy->getVectorNumElements(); 901 return Builder.CreateVectorSplat(NumElements, Src, "splat"); 902 } 903 904 // Allow bitcast from vector to integer/fp of the same size. 905 if (isa<llvm::VectorType>(SrcTy) || 906 isa<llvm::VectorType>(DstTy)) 907 return Builder.CreateBitCast(Src, DstTy, "conv"); 908 909 // Finally, we have the arithmetic types: real int/float. 910 Value *Res = nullptr; 911 llvm::Type *ResTy = DstTy; 912 913 // An overflowing conversion has undefined behavior if either the source type 914 // or the destination type is a floating-point type. 915 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) && 916 (OrigSrcType->isFloatingType() || DstType->isFloatingType())) 917 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy, 918 Loc); 919 920 // Cast to half through float if half isn't a native type. 921 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 922 // Make sure we cast in a single step if from another FP type. 923 if (SrcTy->isFloatingPointTy()) { 924 // Use the intrinsic if the half type itself isn't supported 925 // (as opposed to operations on half, available with NativeHalfType). 926 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) 927 return Builder.CreateCall( 928 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src); 929 // If the half type is supported, just use an fptrunc. 930 return Builder.CreateFPTrunc(Src, DstTy); 931 } 932 DstTy = CGF.FloatTy; 933 } 934 935 if (isa<llvm::IntegerType>(SrcTy)) { 936 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); 937 if (SrcType->isBooleanType() && TreatBooleanAsSigned) { 938 InputSigned = true; 939 } 940 if (isa<llvm::IntegerType>(DstTy)) 941 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 942 else if (InputSigned) 943 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 944 else 945 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 946 } else if (isa<llvm::IntegerType>(DstTy)) { 947 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion"); 948 if (DstType->isSignedIntegerOrEnumerationType()) 949 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 950 else 951 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 952 } else { 953 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() && 954 "Unknown real conversion"); 955 if (DstTy->getTypeID() < SrcTy->getTypeID()) 956 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 957 else 958 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 959 } 960 961 if (DstTy != ResTy) { 962 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 963 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion"); 964 Res = Builder.CreateCall( 965 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy), 966 Res); 967 } else { 968 Res = Builder.CreateFPTrunc(Res, ResTy, "conv"); 969 } 970 } 971 972 return Res; 973 } 974 975 /// Emit a conversion from the specified complex type to the specified 976 /// destination type, where the destination type is an LLVM scalar type. 977 Value *ScalarExprEmitter::EmitComplexToScalarConversion( 978 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy, 979 SourceLocation Loc) { 980 // Get the source element type. 981 SrcTy = SrcTy->castAs<ComplexType>()->getElementType(); 982 983 // Handle conversions to bool first, they are special: comparisons against 0. 984 if (DstTy->isBooleanType()) { 985 // Complex != 0 -> (Real != 0) | (Imag != 0) 986 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 987 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc); 988 return Builder.CreateOr(Src.first, Src.second, "tobool"); 989 } 990 991 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 992 // the imaginary part of the complex value is discarded and the value of the 993 // real part is converted according to the conversion rules for the 994 // corresponding real type. 995 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc); 996 } 997 998 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) { 999 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty); 1000 } 1001 1002 /// \brief Emit a sanitization check for the given "binary" operation (which 1003 /// might actually be a unary increment which has been lowered to a binary 1004 /// operation). The check passes if all values in \p Checks (which are \c i1), 1005 /// are \c true. 1006 void ScalarExprEmitter::EmitBinOpCheck( 1007 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) { 1008 assert(CGF.IsSanitizerScope); 1009 SanitizerHandler Check; 1010 SmallVector<llvm::Constant *, 4> StaticData; 1011 SmallVector<llvm::Value *, 2> DynamicData; 1012 1013 BinaryOperatorKind Opcode = Info.Opcode; 1014 if (BinaryOperator::isCompoundAssignmentOp(Opcode)) 1015 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode); 1016 1017 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc())); 1018 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E); 1019 if (UO && UO->getOpcode() == UO_Minus) { 1020 Check = SanitizerHandler::NegateOverflow; 1021 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType())); 1022 DynamicData.push_back(Info.RHS); 1023 } else { 1024 if (BinaryOperator::isShiftOp(Opcode)) { 1025 // Shift LHS negative or too large, or RHS out of bounds. 1026 Check = SanitizerHandler::ShiftOutOfBounds; 1027 const BinaryOperator *BO = cast<BinaryOperator>(Info.E); 1028 StaticData.push_back( 1029 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType())); 1030 StaticData.push_back( 1031 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType())); 1032 } else if (Opcode == BO_Div || Opcode == BO_Rem) { 1033 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1). 1034 Check = SanitizerHandler::DivremOverflow; 1035 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1036 } else { 1037 // Arithmetic overflow (+, -, *). 1038 switch (Opcode) { 1039 case BO_Add: Check = SanitizerHandler::AddOverflow; break; 1040 case BO_Sub: Check = SanitizerHandler::SubOverflow; break; 1041 case BO_Mul: Check = SanitizerHandler::MulOverflow; break; 1042 default: llvm_unreachable("unexpected opcode for bin op check"); 1043 } 1044 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty)); 1045 } 1046 DynamicData.push_back(Info.LHS); 1047 DynamicData.push_back(Info.RHS); 1048 } 1049 1050 CGF.EmitCheck(Checks, Check, StaticData, DynamicData); 1051 } 1052 1053 //===----------------------------------------------------------------------===// 1054 // Visitor Methods 1055 //===----------------------------------------------------------------------===// 1056 1057 Value *ScalarExprEmitter::VisitExpr(Expr *E) { 1058 CGF.ErrorUnsupported(E, "scalar expression"); 1059 if (E->getType()->isVoidType()) 1060 return nullptr; 1061 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 1062 } 1063 1064 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 1065 // Vector Mask Case 1066 if (E->getNumSubExprs() == 2) { 1067 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0)); 1068 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1)); 1069 Value *Mask; 1070 1071 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType()); 1072 unsigned LHSElts = LTy->getNumElements(); 1073 1074 Mask = RHS; 1075 1076 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType()); 1077 1078 // Mask off the high bits of each shuffle index. 1079 Value *MaskBits = 1080 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1); 1081 Mask = Builder.CreateAnd(Mask, MaskBits, "mask"); 1082 1083 // newv = undef 1084 // mask = mask & maskbits 1085 // for each elt 1086 // n = extract mask i 1087 // x = extract val n 1088 // newv = insert newv, x, i 1089 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(), 1090 MTy->getNumElements()); 1091 Value* NewV = llvm::UndefValue::get(RTy); 1092 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) { 1093 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i); 1094 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx"); 1095 1096 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt"); 1097 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins"); 1098 } 1099 return NewV; 1100 } 1101 1102 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 1103 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 1104 1105 SmallVector<llvm::Constant*, 32> indices; 1106 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) { 1107 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2); 1108 // Check for -1 and output it as undef in the IR. 1109 if (Idx.isSigned() && Idx.isAllOnesValue()) 1110 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 1111 else 1112 indices.push_back(Builder.getInt32(Idx.getZExtValue())); 1113 } 1114 1115 Value *SV = llvm::ConstantVector::get(indices); 1116 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 1117 } 1118 1119 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) { 1120 QualType SrcType = E->getSrcExpr()->getType(), 1121 DstType = E->getType(); 1122 1123 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 1124 1125 SrcType = CGF.getContext().getCanonicalType(SrcType); 1126 DstType = CGF.getContext().getCanonicalType(DstType); 1127 if (SrcType == DstType) return Src; 1128 1129 assert(SrcType->isVectorType() && 1130 "ConvertVector source type must be a vector"); 1131 assert(DstType->isVectorType() && 1132 "ConvertVector destination type must be a vector"); 1133 1134 llvm::Type *SrcTy = Src->getType(); 1135 llvm::Type *DstTy = ConvertType(DstType); 1136 1137 // Ignore conversions like int -> uint. 1138 if (SrcTy == DstTy) 1139 return Src; 1140 1141 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(), 1142 DstEltType = DstType->getAs<VectorType>()->getElementType(); 1143 1144 assert(SrcTy->isVectorTy() && 1145 "ConvertVector source IR type must be a vector"); 1146 assert(DstTy->isVectorTy() && 1147 "ConvertVector destination IR type must be a vector"); 1148 1149 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(), 1150 *DstEltTy = DstTy->getVectorElementType(); 1151 1152 if (DstEltType->isBooleanType()) { 1153 assert((SrcEltTy->isFloatingPointTy() || 1154 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion"); 1155 1156 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy); 1157 if (SrcEltTy->isFloatingPointTy()) { 1158 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 1159 } else { 1160 return Builder.CreateICmpNE(Src, Zero, "tobool"); 1161 } 1162 } 1163 1164 // We have the arithmetic types: real int/float. 1165 Value *Res = nullptr; 1166 1167 if (isa<llvm::IntegerType>(SrcEltTy)) { 1168 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType(); 1169 if (isa<llvm::IntegerType>(DstEltTy)) 1170 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 1171 else if (InputSigned) 1172 Res = Builder.CreateSIToFP(Src, DstTy, "conv"); 1173 else 1174 Res = Builder.CreateUIToFP(Src, DstTy, "conv"); 1175 } else if (isa<llvm::IntegerType>(DstEltTy)) { 1176 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion"); 1177 if (DstEltType->isSignedIntegerOrEnumerationType()) 1178 Res = Builder.CreateFPToSI(Src, DstTy, "conv"); 1179 else 1180 Res = Builder.CreateFPToUI(Src, DstTy, "conv"); 1181 } else { 1182 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() && 1183 "Unknown real conversion"); 1184 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID()) 1185 Res = Builder.CreateFPTrunc(Src, DstTy, "conv"); 1186 else 1187 Res = Builder.CreateFPExt(Src, DstTy, "conv"); 1188 } 1189 1190 return Res; 1191 } 1192 1193 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) { 1194 llvm::APSInt Value; 1195 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) { 1196 if (E->isArrow()) 1197 CGF.EmitScalarExpr(E->getBase()); 1198 else 1199 EmitLValue(E->getBase()); 1200 return Builder.getInt(Value); 1201 } 1202 1203 return EmitLoadOfLValue(E); 1204 } 1205 1206 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 1207 TestAndClearIgnoreResultAssign(); 1208 1209 // Emit subscript expressions in rvalue context's. For most cases, this just 1210 // loads the lvalue formed by the subscript expr. However, we have to be 1211 // careful, because the base of a vector subscript is occasionally an rvalue, 1212 // so we can't get it as an lvalue. 1213 if (!E->getBase()->getType()->isVectorType()) 1214 return EmitLoadOfLValue(E); 1215 1216 // Handle the vector case. The base must be a vector, the index must be an 1217 // integer value. 1218 Value *Base = Visit(E->getBase()); 1219 Value *Idx = Visit(E->getIdx()); 1220 QualType IdxTy = E->getIdx()->getType(); 1221 1222 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 1223 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true); 1224 1225 return Builder.CreateExtractElement(Base, Idx, "vecext"); 1226 } 1227 1228 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, 1229 unsigned Off, llvm::Type *I32Ty) { 1230 int MV = SVI->getMaskValue(Idx); 1231 if (MV == -1) 1232 return llvm::UndefValue::get(I32Ty); 1233 return llvm::ConstantInt::get(I32Ty, Off+MV); 1234 } 1235 1236 static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) { 1237 if (C->getBitWidth() != 32) { 1238 assert(llvm::ConstantInt::isValueValidForType(I32Ty, 1239 C->getZExtValue()) && 1240 "Index operand too large for shufflevector mask!"); 1241 return llvm::ConstantInt::get(I32Ty, C->getZExtValue()); 1242 } 1243 return C; 1244 } 1245 1246 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) { 1247 bool Ignore = TestAndClearIgnoreResultAssign(); 1248 (void)Ignore; 1249 assert (Ignore == false && "init list ignored"); 1250 unsigned NumInitElements = E->getNumInits(); 1251 1252 if (E->hadArrayRangeDesignator()) 1253 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 1254 1255 llvm::VectorType *VType = 1256 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 1257 1258 if (!VType) { 1259 if (NumInitElements == 0) { 1260 // C++11 value-initialization for the scalar. 1261 return EmitNullValue(E->getType()); 1262 } 1263 // We have a scalar in braces. Just use the first element. 1264 return Visit(E->getInit(0)); 1265 } 1266 1267 unsigned ResElts = VType->getNumElements(); 1268 1269 // Loop over initializers collecting the Value for each, and remembering 1270 // whether the source was swizzle (ExtVectorElementExpr). This will allow 1271 // us to fold the shuffle for the swizzle into the shuffle for the vector 1272 // initializer, since LLVM optimizers generally do not want to touch 1273 // shuffles. 1274 unsigned CurIdx = 0; 1275 bool VIsUndefShuffle = false; 1276 llvm::Value *V = llvm::UndefValue::get(VType); 1277 for (unsigned i = 0; i != NumInitElements; ++i) { 1278 Expr *IE = E->getInit(i); 1279 Value *Init = Visit(IE); 1280 SmallVector<llvm::Constant*, 16> Args; 1281 1282 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType()); 1283 1284 // Handle scalar elements. If the scalar initializer is actually one 1285 // element of a different vector of the same width, use shuffle instead of 1286 // extract+insert. 1287 if (!VVT) { 1288 if (isa<ExtVectorElementExpr>(IE)) { 1289 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init); 1290 1291 if (EI->getVectorOperandType()->getNumElements() == ResElts) { 1292 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand()); 1293 Value *LHS = nullptr, *RHS = nullptr; 1294 if (CurIdx == 0) { 1295 // insert into undef -> shuffle (src, undef) 1296 // shufflemask must use an i32 1297 Args.push_back(getAsInt32(C, CGF.Int32Ty)); 1298 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1299 1300 LHS = EI->getVectorOperand(); 1301 RHS = V; 1302 VIsUndefShuffle = true; 1303 } else if (VIsUndefShuffle) { 1304 // insert into undefshuffle && size match -> shuffle (v, src) 1305 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V); 1306 for (unsigned j = 0; j != CurIdx; ++j) 1307 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty)); 1308 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue())); 1309 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1310 1311 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1312 RHS = EI->getVectorOperand(); 1313 VIsUndefShuffle = false; 1314 } 1315 if (!Args.empty()) { 1316 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1317 V = Builder.CreateShuffleVector(LHS, RHS, Mask); 1318 ++CurIdx; 1319 continue; 1320 } 1321 } 1322 } 1323 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx), 1324 "vecinit"); 1325 VIsUndefShuffle = false; 1326 ++CurIdx; 1327 continue; 1328 } 1329 1330 unsigned InitElts = VVT->getNumElements(); 1331 1332 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's 1333 // input is the same width as the vector being constructed, generate an 1334 // optimized shuffle of the swizzle input into the result. 1335 unsigned Offset = (CurIdx == 0) ? 0 : ResElts; 1336 if (isa<ExtVectorElementExpr>(IE)) { 1337 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init); 1338 Value *SVOp = SVI->getOperand(0); 1339 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType()); 1340 1341 if (OpTy->getNumElements() == ResElts) { 1342 for (unsigned j = 0; j != CurIdx; ++j) { 1343 // If the current vector initializer is a shuffle with undef, merge 1344 // this shuffle directly into it. 1345 if (VIsUndefShuffle) { 1346 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0, 1347 CGF.Int32Ty)); 1348 } else { 1349 Args.push_back(Builder.getInt32(j)); 1350 } 1351 } 1352 for (unsigned j = 0, je = InitElts; j != je; ++j) 1353 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty)); 1354 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1355 1356 if (VIsUndefShuffle) 1357 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0); 1358 1359 Init = SVOp; 1360 } 1361 } 1362 1363 // Extend init to result vector length, and then shuffle its contribution 1364 // to the vector initializer into V. 1365 if (Args.empty()) { 1366 for (unsigned j = 0; j != InitElts; ++j) 1367 Args.push_back(Builder.getInt32(j)); 1368 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1369 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1370 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT), 1371 Mask, "vext"); 1372 1373 Args.clear(); 1374 for (unsigned j = 0; j != CurIdx; ++j) 1375 Args.push_back(Builder.getInt32(j)); 1376 for (unsigned j = 0; j != InitElts; ++j) 1377 Args.push_back(Builder.getInt32(j+Offset)); 1378 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty)); 1379 } 1380 1381 // If V is undef, make sure it ends up on the RHS of the shuffle to aid 1382 // merging subsequent shuffles into this one. 1383 if (CurIdx == 0) 1384 std::swap(V, Init); 1385 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 1386 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit"); 1387 VIsUndefShuffle = isa<llvm::UndefValue>(Init); 1388 CurIdx += InitElts; 1389 } 1390 1391 // FIXME: evaluate codegen vs. shuffling against constant null vector. 1392 // Emit remaining default initializers. 1393 llvm::Type *EltTy = VType->getElementType(); 1394 1395 // Emit remaining default initializers 1396 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) { 1397 Value *Idx = Builder.getInt32(CurIdx); 1398 llvm::Value *Init = llvm::Constant::getNullValue(EltTy); 1399 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit"); 1400 } 1401 return V; 1402 } 1403 1404 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) { 1405 const Expr *E = CE->getSubExpr(); 1406 1407 if (CE->getCastKind() == CK_UncheckedDerivedToBase) 1408 return false; 1409 1410 if (isa<CXXThisExpr>(E->IgnoreParens())) { 1411 // We always assume that 'this' is never null. 1412 return false; 1413 } 1414 1415 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) { 1416 // And that glvalue casts are never null. 1417 if (ICE->getValueKind() != VK_RValue) 1418 return false; 1419 } 1420 1421 return true; 1422 } 1423 1424 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 1425 // have to handle a more broad range of conversions than explicit casts, as they 1426 // handle things like function to ptr-to-function decay etc. 1427 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { 1428 Expr *E = CE->getSubExpr(); 1429 QualType DestTy = CE->getType(); 1430 CastKind Kind = CE->getCastKind(); 1431 1432 // These cases are generally not written to ignore the result of 1433 // evaluating their sub-expressions, so we clear this now. 1434 bool Ignored = TestAndClearIgnoreResultAssign(); 1435 1436 // Since almost all cast kinds apply to scalars, this switch doesn't have 1437 // a default case, so the compiler will warn on a missing case. The cases 1438 // are in the same order as in the CastKind enum. 1439 switch (Kind) { 1440 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!"); 1441 case CK_BuiltinFnToFnPtr: 1442 llvm_unreachable("builtin functions are handled elsewhere"); 1443 1444 case CK_LValueBitCast: 1445 case CK_ObjCObjectLValueCast: { 1446 Address Addr = EmitLValue(E).getAddress(); 1447 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy)); 1448 LValue LV = CGF.MakeAddrLValue(Addr, DestTy); 1449 return EmitLoadOfLValue(LV, CE->getExprLoc()); 1450 } 1451 1452 case CK_CPointerToObjCPointerCast: 1453 case CK_BlockPointerToObjCPointerCast: 1454 case CK_AnyPointerToBlockPointerCast: 1455 case CK_BitCast: { 1456 Value *Src = Visit(const_cast<Expr*>(E)); 1457 llvm::Type *SrcTy = Src->getType(); 1458 llvm::Type *DstTy = ConvertType(DestTy); 1459 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() && 1460 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) { 1461 llvm_unreachable("wrong cast for pointers in different address spaces" 1462 "(must be an address space cast)!"); 1463 } 1464 1465 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 1466 if (auto PT = DestTy->getAs<PointerType>()) 1467 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src, 1468 /*MayBeNull=*/true, 1469 CodeGenFunction::CFITCK_UnrelatedCast, 1470 CE->getLocStart()); 1471 } 1472 1473 return Builder.CreateBitCast(Src, DstTy); 1474 } 1475 case CK_AddressSpaceConversion: { 1476 Expr::EvalResult Result; 1477 if (E->EvaluateAsRValue(Result, CGF.getContext()) && 1478 Result.Val.isNullPointer()) { 1479 // If E has side effect, it is emitted even if its final result is a 1480 // null pointer. In that case, a DCE pass should be able to 1481 // eliminate the useless instructions emitted during translating E. 1482 if (Result.HasSideEffects) 1483 Visit(E); 1484 return CGF.CGM.getNullPointer(cast<llvm::PointerType>( 1485 ConvertType(DestTy)), DestTy); 1486 } 1487 // Since target may map different address spaces in AST to the same address 1488 // space, an address space conversion may end up as a bitcast. 1489 auto *Src = Visit(E); 1490 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGF, Src, 1491 E->getType(), 1492 DestTy); 1493 } 1494 case CK_AtomicToNonAtomic: 1495 case CK_NonAtomicToAtomic: 1496 case CK_NoOp: 1497 case CK_UserDefinedConversion: 1498 return Visit(const_cast<Expr*>(E)); 1499 1500 case CK_BaseToDerived: { 1501 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl(); 1502 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!"); 1503 1504 Address Base = CGF.EmitPointerWithAlignment(E); 1505 Address Derived = 1506 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl, 1507 CE->path_begin(), CE->path_end(), 1508 CGF.ShouldNullCheckClassCastValue(CE)); 1509 1510 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is 1511 // performed and the object is not of the derived type. 1512 if (CGF.sanitizePerformTypeCheck()) 1513 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(), 1514 Derived.getPointer(), DestTy->getPointeeType()); 1515 1516 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast)) 1517 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), 1518 Derived.getPointer(), 1519 /*MayBeNull=*/true, 1520 CodeGenFunction::CFITCK_DerivedCast, 1521 CE->getLocStart()); 1522 1523 return Derived.getPointer(); 1524 } 1525 case CK_UncheckedDerivedToBase: 1526 case CK_DerivedToBase: { 1527 // The EmitPointerWithAlignment path does this fine; just discard 1528 // the alignment. 1529 return CGF.EmitPointerWithAlignment(CE).getPointer(); 1530 } 1531 1532 case CK_Dynamic: { 1533 Address V = CGF.EmitPointerWithAlignment(E); 1534 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE); 1535 return CGF.EmitDynamicCast(V, DCE); 1536 } 1537 1538 case CK_ArrayToPointerDecay: 1539 return CGF.EmitArrayToPointerDecay(E).getPointer(); 1540 case CK_FunctionToPointerDecay: 1541 return EmitLValue(E).getPointer(); 1542 1543 case CK_NullToPointer: 1544 if (MustVisitNullValue(E)) 1545 (void) Visit(E); 1546 1547 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)), 1548 DestTy); 1549 1550 case CK_NullToMemberPointer: { 1551 if (MustVisitNullValue(E)) 1552 (void) Visit(E); 1553 1554 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>(); 1555 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT); 1556 } 1557 1558 case CK_ReinterpretMemberPointer: 1559 case CK_BaseToDerivedMemberPointer: 1560 case CK_DerivedToBaseMemberPointer: { 1561 Value *Src = Visit(E); 1562 1563 // Note that the AST doesn't distinguish between checked and 1564 // unchecked member pointer conversions, so we always have to 1565 // implement checked conversions here. This is inefficient when 1566 // actual control flow may be required in order to perform the 1567 // check, which it is for data member pointers (but not member 1568 // function pointers on Itanium and ARM). 1569 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src); 1570 } 1571 1572 case CK_ARCProduceObject: 1573 return CGF.EmitARCRetainScalarExpr(E); 1574 case CK_ARCConsumeObject: 1575 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E)); 1576 case CK_ARCReclaimReturnedObject: 1577 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored); 1578 case CK_ARCExtendBlockObject: 1579 return CGF.EmitARCExtendBlockObject(E); 1580 1581 case CK_CopyAndAutoreleaseBlockObject: 1582 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType()); 1583 1584 case CK_FloatingRealToComplex: 1585 case CK_FloatingComplexCast: 1586 case CK_IntegralRealToComplex: 1587 case CK_IntegralComplexCast: 1588 case CK_IntegralComplexToFloatingComplex: 1589 case CK_FloatingComplexToIntegralComplex: 1590 case CK_ConstructorConversion: 1591 case CK_ToUnion: 1592 llvm_unreachable("scalar cast to non-scalar value"); 1593 1594 case CK_LValueToRValue: 1595 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy)); 1596 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!"); 1597 return Visit(const_cast<Expr*>(E)); 1598 1599 case CK_IntegralToPointer: { 1600 Value *Src = Visit(const_cast<Expr*>(E)); 1601 1602 // First, convert to the correct width so that we control the kind of 1603 // extension. 1604 auto DestLLVMTy = ConvertType(DestTy); 1605 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy); 1606 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType(); 1607 llvm::Value* IntResult = 1608 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 1609 1610 return Builder.CreateIntToPtr(IntResult, DestLLVMTy); 1611 } 1612 case CK_PointerToIntegral: 1613 assert(!DestTy->isBooleanType() && "bool should use PointerToBool"); 1614 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy)); 1615 1616 case CK_ToVoid: { 1617 CGF.EmitIgnoredExpr(E); 1618 return nullptr; 1619 } 1620 case CK_VectorSplat: { 1621 llvm::Type *DstTy = ConvertType(DestTy); 1622 Value *Elt = Visit(const_cast<Expr*>(E)); 1623 // Splat the element across to all elements 1624 unsigned NumElements = DstTy->getVectorNumElements(); 1625 return Builder.CreateVectorSplat(NumElements, Elt, "splat"); 1626 } 1627 1628 case CK_IntegralCast: 1629 case CK_IntegralToFloating: 1630 case CK_FloatingToIntegral: 1631 case CK_FloatingCast: 1632 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 1633 CE->getExprLoc()); 1634 case CK_BooleanToSignedIntegral: 1635 return EmitScalarConversion(Visit(E), E->getType(), DestTy, 1636 CE->getExprLoc(), 1637 /*TreatBooleanAsSigned=*/true); 1638 case CK_IntegralToBoolean: 1639 return EmitIntToBoolConversion(Visit(E)); 1640 case CK_PointerToBoolean: 1641 return EmitPointerToBoolConversion(Visit(E), E->getType()); 1642 case CK_FloatingToBoolean: 1643 return EmitFloatToBoolConversion(Visit(E)); 1644 case CK_MemberPointerToBoolean: { 1645 llvm::Value *MemPtr = Visit(E); 1646 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 1647 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 1648 } 1649 1650 case CK_FloatingComplexToReal: 1651 case CK_IntegralComplexToReal: 1652 return CGF.EmitComplexExpr(E, false, true).first; 1653 1654 case CK_FloatingComplexToBoolean: 1655 case CK_IntegralComplexToBoolean: { 1656 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E); 1657 1658 // TODO: kill this function off, inline appropriate case here 1659 return EmitComplexToScalarConversion(V, E->getType(), DestTy, 1660 CE->getExprLoc()); 1661 } 1662 1663 case CK_ZeroToOCLEvent: { 1664 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type"); 1665 return llvm::Constant::getNullValue(ConvertType(DestTy)); 1666 } 1667 1668 case CK_ZeroToOCLQueue: { 1669 assert(DestTy->isQueueT() && "CK_ZeroToOCLQueue cast on non queue_t type"); 1670 return llvm::Constant::getNullValue(ConvertType(DestTy)); 1671 } 1672 1673 case CK_IntToOCLSampler: 1674 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF); 1675 1676 } // end of switch 1677 1678 llvm_unreachable("unknown scalar cast"); 1679 } 1680 1681 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 1682 CodeGenFunction::StmtExprEvaluation eval(CGF); 1683 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), 1684 !E->getType()->isVoidType()); 1685 if (!RetAlloca.isValid()) 1686 return nullptr; 1687 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()), 1688 E->getExprLoc()); 1689 } 1690 1691 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 1692 CGF.enterFullExpression(E); 1693 CodeGenFunction::RunCleanupsScope Scope(CGF); 1694 Value *V = Visit(E->getSubExpr()); 1695 // Defend against dominance problems caused by jumps out of expression 1696 // evaluation through the shared cleanup block. 1697 Scope.ForceCleanup({&V}); 1698 return V; 1699 } 1700 1701 //===----------------------------------------------------------------------===// 1702 // Unary Operators 1703 //===----------------------------------------------------------------------===// 1704 1705 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, 1706 llvm::Value *InVal, bool IsInc) { 1707 BinOpInfo BinOp; 1708 BinOp.LHS = InVal; 1709 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false); 1710 BinOp.Ty = E->getType(); 1711 BinOp.Opcode = IsInc ? BO_Add : BO_Sub; 1712 BinOp.FPContractable = false; 1713 BinOp.E = E; 1714 return BinOp; 1715 } 1716 1717 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior( 1718 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) { 1719 llvm::Value *Amount = 1720 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true); 1721 StringRef Name = IsInc ? "inc" : "dec"; 1722 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 1723 case LangOptions::SOB_Defined: 1724 return Builder.CreateAdd(InVal, Amount, Name); 1725 case LangOptions::SOB_Undefined: 1726 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 1727 return Builder.CreateNSWAdd(InVal, Amount, Name); 1728 // Fall through. 1729 case LangOptions::SOB_Trapping: 1730 if (IsWidenedIntegerOp(CGF.getContext(), E->getSubExpr())) 1731 return Builder.CreateNSWAdd(InVal, Amount, Name); 1732 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc)); 1733 } 1734 llvm_unreachable("Unknown SignedOverflowBehaviorTy"); 1735 } 1736 1737 llvm::Value * 1738 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1739 bool isInc, bool isPre) { 1740 1741 QualType type = E->getSubExpr()->getType(); 1742 llvm::PHINode *atomicPHI = nullptr; 1743 llvm::Value *value; 1744 llvm::Value *input; 1745 1746 int amount = (isInc ? 1 : -1); 1747 1748 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) { 1749 type = atomicTy->getValueType(); 1750 if (isInc && type->isBooleanType()) { 1751 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type); 1752 if (isPre) { 1753 Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified()) 1754 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent); 1755 return Builder.getTrue(); 1756 } 1757 // For atomic bool increment, we just store true and return it for 1758 // preincrement, do an atomic swap with true for postincrement 1759 return Builder.CreateAtomicRMW( 1760 llvm::AtomicRMWInst::Xchg, LV.getPointer(), True, 1761 llvm::AtomicOrdering::SequentiallyConsistent); 1762 } 1763 // Special case for atomic increment / decrement on integers, emit 1764 // atomicrmw instructions. We skip this if we want to be doing overflow 1765 // checking, and fall into the slow path with the atomic cmpxchg loop. 1766 if (!type->isBooleanType() && type->isIntegerType() && 1767 !(type->isUnsignedIntegerType() && 1768 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 1769 CGF.getLangOpts().getSignedOverflowBehavior() != 1770 LangOptions::SOB_Trapping) { 1771 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add : 1772 llvm::AtomicRMWInst::Sub; 1773 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add : 1774 llvm::Instruction::Sub; 1775 llvm::Value *amt = CGF.EmitToMemory( 1776 llvm::ConstantInt::get(ConvertType(type), 1, true), type); 1777 llvm::Value *old = Builder.CreateAtomicRMW(aop, 1778 LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent); 1779 return isPre ? Builder.CreateBinOp(op, old, amt) : old; 1780 } 1781 value = EmitLoadOfLValue(LV, E->getExprLoc()); 1782 input = value; 1783 // For every other atomic operation, we need to emit a load-op-cmpxchg loop 1784 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 1785 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 1786 value = CGF.EmitToMemory(value, type); 1787 Builder.CreateBr(opBB); 1788 Builder.SetInsertPoint(opBB); 1789 atomicPHI = Builder.CreatePHI(value->getType(), 2); 1790 atomicPHI->addIncoming(value, startBB); 1791 value = atomicPHI; 1792 } else { 1793 value = EmitLoadOfLValue(LV, E->getExprLoc()); 1794 input = value; 1795 } 1796 1797 // Special case of integer increment that we have to check first: bool++. 1798 // Due to promotion rules, we get: 1799 // bool++ -> bool = bool + 1 1800 // -> bool = (int)bool + 1 1801 // -> bool = ((int)bool + 1 != 0) 1802 // An interesting aspect of this is that increment is always true. 1803 // Decrement does not have this property. 1804 if (isInc && type->isBooleanType()) { 1805 value = Builder.getTrue(); 1806 1807 // Most common case by far: integer increment. 1808 } else if (type->isIntegerType()) { 1809 // Note that signed integer inc/dec with width less than int can't 1810 // overflow because of promotion rules; we're just eliding a few steps here. 1811 bool CanOverflow = value->getType()->getIntegerBitWidth() >= 1812 CGF.IntTy->getIntegerBitWidth(); 1813 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) { 1814 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc); 1815 } else if (CanOverflow && type->isUnsignedIntegerType() && 1816 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) { 1817 value = 1818 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc)); 1819 } else { 1820 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true); 1821 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1822 } 1823 1824 // Next most common: pointer increment. 1825 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 1826 QualType type = ptr->getPointeeType(); 1827 1828 // VLA types don't have constant size. 1829 if (const VariableArrayType *vla 1830 = CGF.getContext().getAsVariableArrayType(type)) { 1831 llvm::Value *numElts = CGF.getVLASize(vla).first; 1832 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize"); 1833 if (CGF.getLangOpts().isSignedOverflowDefined()) 1834 value = Builder.CreateGEP(value, numElts, "vla.inc"); 1835 else 1836 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc"); 1837 1838 // Arithmetic on function pointers (!) is just +-1. 1839 } else if (type->isFunctionType()) { 1840 llvm::Value *amt = Builder.getInt32(amount); 1841 1842 value = CGF.EmitCastToVoidPtr(value); 1843 if (CGF.getLangOpts().isSignedOverflowDefined()) 1844 value = Builder.CreateGEP(value, amt, "incdec.funcptr"); 1845 else 1846 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr"); 1847 value = Builder.CreateBitCast(value, input->getType()); 1848 1849 // For everything else, we can just do a simple increment. 1850 } else { 1851 llvm::Value *amt = Builder.getInt32(amount); 1852 if (CGF.getLangOpts().isSignedOverflowDefined()) 1853 value = Builder.CreateGEP(value, amt, "incdec.ptr"); 1854 else 1855 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr"); 1856 } 1857 1858 // Vector increment/decrement. 1859 } else if (type->isVectorType()) { 1860 if (type->hasIntegerRepresentation()) { 1861 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount); 1862 1863 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec"); 1864 } else { 1865 value = Builder.CreateFAdd( 1866 value, 1867 llvm::ConstantFP::get(value->getType(), amount), 1868 isInc ? "inc" : "dec"); 1869 } 1870 1871 // Floating point. 1872 } else if (type->isRealFloatingType()) { 1873 // Add the inc/dec to the real part. 1874 llvm::Value *amt; 1875 1876 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1877 // Another special case: half FP increment should be done via float 1878 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 1879 value = Builder.CreateCall( 1880 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, 1881 CGF.CGM.FloatTy), 1882 input, "incdec.conv"); 1883 } else { 1884 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv"); 1885 } 1886 } 1887 1888 if (value->getType()->isFloatTy()) 1889 amt = llvm::ConstantFP::get(VMContext, 1890 llvm::APFloat(static_cast<float>(amount))); 1891 else if (value->getType()->isDoubleTy()) 1892 amt = llvm::ConstantFP::get(VMContext, 1893 llvm::APFloat(static_cast<double>(amount))); 1894 else { 1895 // Remaining types are Half, LongDouble or __float128. Convert from float. 1896 llvm::APFloat F(static_cast<float>(amount)); 1897 bool ignored; 1898 const llvm::fltSemantics *FS; 1899 // Don't use getFloatTypeSemantics because Half isn't 1900 // necessarily represented using the "half" LLVM type. 1901 if (value->getType()->isFP128Ty()) 1902 FS = &CGF.getTarget().getFloat128Format(); 1903 else if (value->getType()->isHalfTy()) 1904 FS = &CGF.getTarget().getHalfFormat(); 1905 else 1906 FS = &CGF.getTarget().getLongDoubleFormat(); 1907 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored); 1908 amt = llvm::ConstantFP::get(VMContext, F); 1909 } 1910 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec"); 1911 1912 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) { 1913 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) { 1914 value = Builder.CreateCall( 1915 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, 1916 CGF.CGM.FloatTy), 1917 value, "incdec.conv"); 1918 } else { 1919 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv"); 1920 } 1921 } 1922 1923 // Objective-C pointer types. 1924 } else { 1925 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>(); 1926 value = CGF.EmitCastToVoidPtr(value); 1927 1928 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType()); 1929 if (!isInc) size = -size; 1930 llvm::Value *sizeValue = 1931 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity()); 1932 1933 if (CGF.getLangOpts().isSignedOverflowDefined()) 1934 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr"); 1935 else 1936 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr"); 1937 value = Builder.CreateBitCast(value, input->getType()); 1938 } 1939 1940 if (atomicPHI) { 1941 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 1942 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 1943 auto Pair = CGF.EmitAtomicCompareExchange( 1944 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc()); 1945 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type); 1946 llvm::Value *success = Pair.second; 1947 atomicPHI->addIncoming(old, opBB); 1948 Builder.CreateCondBr(success, contBB, opBB); 1949 Builder.SetInsertPoint(contBB); 1950 return isPre ? value : input; 1951 } 1952 1953 // Store the updated result through the lvalue. 1954 if (LV.isBitField()) 1955 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value); 1956 else 1957 CGF.EmitStoreThroughLValue(RValue::get(value), LV); 1958 1959 // If this is a postinc, return the value read from memory, otherwise use the 1960 // updated value. 1961 return isPre ? value : input; 1962 } 1963 1964 1965 1966 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 1967 TestAndClearIgnoreResultAssign(); 1968 // Emit unary minus with EmitSub so we handle overflow cases etc. 1969 BinOpInfo BinOp; 1970 BinOp.RHS = Visit(E->getSubExpr()); 1971 1972 if (BinOp.RHS->getType()->isFPOrFPVectorTy()) 1973 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType()); 1974 else 1975 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType()); 1976 BinOp.Ty = E->getType(); 1977 BinOp.Opcode = BO_Sub; 1978 BinOp.FPContractable = false; 1979 BinOp.E = E; 1980 return EmitSub(BinOp); 1981 } 1982 1983 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 1984 TestAndClearIgnoreResultAssign(); 1985 Value *Op = Visit(E->getSubExpr()); 1986 return Builder.CreateNot(Op, "neg"); 1987 } 1988 1989 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 1990 // Perform vector logical not on comparison with zero vector. 1991 if (E->getType()->isExtVectorType()) { 1992 Value *Oper = Visit(E->getSubExpr()); 1993 Value *Zero = llvm::Constant::getNullValue(Oper->getType()); 1994 Value *Result; 1995 if (Oper->getType()->isFPOrFPVectorTy()) 1996 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp"); 1997 else 1998 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp"); 1999 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 2000 } 2001 2002 // Compare operand to zero. 2003 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 2004 2005 // Invert value. 2006 // TODO: Could dynamically modify easy computations here. For example, if 2007 // the operand is an icmp ne, turn into icmp eq. 2008 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 2009 2010 // ZExt result to the expr type. 2011 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 2012 } 2013 2014 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) { 2015 // Try folding the offsetof to a constant. 2016 llvm::APSInt Value; 2017 if (E->EvaluateAsInt(Value, CGF.getContext())) 2018 return Builder.getInt(Value); 2019 2020 // Loop over the components of the offsetof to compute the value. 2021 unsigned n = E->getNumComponents(); 2022 llvm::Type* ResultType = ConvertType(E->getType()); 2023 llvm::Value* Result = llvm::Constant::getNullValue(ResultType); 2024 QualType CurrentType = E->getTypeSourceInfo()->getType(); 2025 for (unsigned i = 0; i != n; ++i) { 2026 OffsetOfNode ON = E->getComponent(i); 2027 llvm::Value *Offset = nullptr; 2028 switch (ON.getKind()) { 2029 case OffsetOfNode::Array: { 2030 // Compute the index 2031 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex()); 2032 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr); 2033 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType(); 2034 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv"); 2035 2036 // Save the element type 2037 CurrentType = 2038 CGF.getContext().getAsArrayType(CurrentType)->getElementType(); 2039 2040 // Compute the element size 2041 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType, 2042 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity()); 2043 2044 // Multiply out to compute the result 2045 Offset = Builder.CreateMul(Idx, ElemSize); 2046 break; 2047 } 2048 2049 case OffsetOfNode::Field: { 2050 FieldDecl *MemberDecl = ON.getField(); 2051 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 2052 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2053 2054 // Compute the index of the field in its parent. 2055 unsigned i = 0; 2056 // FIXME: It would be nice if we didn't have to loop here! 2057 for (RecordDecl::field_iterator Field = RD->field_begin(), 2058 FieldEnd = RD->field_end(); 2059 Field != FieldEnd; ++Field, ++i) { 2060 if (*Field == MemberDecl) 2061 break; 2062 } 2063 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 2064 2065 // Compute the offset to the field 2066 int64_t OffsetInt = RL.getFieldOffset(i) / 2067 CGF.getContext().getCharWidth(); 2068 Offset = llvm::ConstantInt::get(ResultType, OffsetInt); 2069 2070 // Save the element type. 2071 CurrentType = MemberDecl->getType(); 2072 break; 2073 } 2074 2075 case OffsetOfNode::Identifier: 2076 llvm_unreachable("dependent __builtin_offsetof"); 2077 2078 case OffsetOfNode::Base: { 2079 if (ON.getBase()->isVirtual()) { 2080 CGF.ErrorUnsupported(E, "virtual base in offsetof"); 2081 continue; 2082 } 2083 2084 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl(); 2085 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD); 2086 2087 // Save the element type. 2088 CurrentType = ON.getBase()->getType(); 2089 2090 // Compute the offset to the base. 2091 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 2092 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl()); 2093 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD); 2094 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity()); 2095 break; 2096 } 2097 } 2098 Result = Builder.CreateAdd(Result, Offset); 2099 } 2100 return Result; 2101 } 2102 2103 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of 2104 /// argument of the sizeof expression as an integer. 2105 Value * 2106 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr( 2107 const UnaryExprOrTypeTraitExpr *E) { 2108 QualType TypeToSize = E->getTypeOfArgument(); 2109 if (E->getKind() == UETT_SizeOf) { 2110 if (const VariableArrayType *VAT = 2111 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 2112 if (E->isArgumentType()) { 2113 // sizeof(type) - make sure to emit the VLA size. 2114 CGF.EmitVariablyModifiedType(TypeToSize); 2115 } else { 2116 // C99 6.5.3.4p2: If the argument is an expression of type 2117 // VLA, it is evaluated. 2118 CGF.EmitIgnoredExpr(E->getArgumentExpr()); 2119 } 2120 2121 QualType eltType; 2122 llvm::Value *numElts; 2123 std::tie(numElts, eltType) = CGF.getVLASize(VAT); 2124 2125 llvm::Value *size = numElts; 2126 2127 // Scale the number of non-VLA elements by the non-VLA element size. 2128 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 2129 if (!eltSize.isOne()) 2130 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts); 2131 2132 return size; 2133 } 2134 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) { 2135 auto Alignment = 2136 CGF.getContext() 2137 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2138 E->getTypeOfArgument()->getPointeeType())) 2139 .getQuantity(); 2140 return llvm::ConstantInt::get(CGF.SizeTy, Alignment); 2141 } 2142 2143 // If this isn't sizeof(vla), the result must be constant; use the constant 2144 // folding logic so we don't have to duplicate it here. 2145 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext())); 2146 } 2147 2148 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 2149 Expr *Op = E->getSubExpr(); 2150 if (Op->getType()->isAnyComplexType()) { 2151 // If it's an l-value, load through the appropriate subobject l-value. 2152 // Note that we have to ask E because Op might be an l-value that 2153 // this won't work for, e.g. an Obj-C property. 2154 if (E->isGLValue()) 2155 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2156 E->getExprLoc()).getScalarVal(); 2157 2158 // Otherwise, calculate and project. 2159 return CGF.EmitComplexExpr(Op, false, true).first; 2160 } 2161 2162 return Visit(Op); 2163 } 2164 2165 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 2166 Expr *Op = E->getSubExpr(); 2167 if (Op->getType()->isAnyComplexType()) { 2168 // If it's an l-value, load through the appropriate subobject l-value. 2169 // Note that we have to ask E because Op might be an l-value that 2170 // this won't work for, e.g. an Obj-C property. 2171 if (Op->isGLValue()) 2172 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), 2173 E->getExprLoc()).getScalarVal(); 2174 2175 // Otherwise, calculate and project. 2176 return CGF.EmitComplexExpr(Op, true, false).second; 2177 } 2178 2179 // __imag on a scalar returns zero. Emit the subexpr to ensure side 2180 // effects are evaluated, but not the actual value. 2181 if (Op->isGLValue()) 2182 CGF.EmitLValue(Op); 2183 else 2184 CGF.EmitScalarExpr(Op, true); 2185 return llvm::Constant::getNullValue(ConvertType(E->getType())); 2186 } 2187 2188 //===----------------------------------------------------------------------===// 2189 // Binary Operators 2190 //===----------------------------------------------------------------------===// 2191 2192 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 2193 TestAndClearIgnoreResultAssign(); 2194 BinOpInfo Result; 2195 Result.LHS = Visit(E->getLHS()); 2196 Result.RHS = Visit(E->getRHS()); 2197 Result.Ty = E->getType(); 2198 Result.Opcode = E->getOpcode(); 2199 Result.FPContractable = E->isFPContractable(); 2200 Result.E = E; 2201 return Result; 2202 } 2203 2204 LValue ScalarExprEmitter::EmitCompoundAssignLValue( 2205 const CompoundAssignOperator *E, 2206 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &), 2207 Value *&Result) { 2208 QualType LHSTy = E->getLHS()->getType(); 2209 BinOpInfo OpInfo; 2210 2211 if (E->getComputationResultType()->isAnyComplexType()) 2212 return CGF.EmitScalarCompoundAssignWithComplex(E, Result); 2213 2214 // Emit the RHS first. __block variables need to have the rhs evaluated 2215 // first, plus this should improve codegen a little. 2216 OpInfo.RHS = Visit(E->getRHS()); 2217 OpInfo.Ty = E->getComputationResultType(); 2218 OpInfo.Opcode = E->getOpcode(); 2219 OpInfo.FPContractable = E->isFPContractable(); 2220 OpInfo.E = E; 2221 // Load/convert the LHS. 2222 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 2223 2224 llvm::PHINode *atomicPHI = nullptr; 2225 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) { 2226 QualType type = atomicTy->getValueType(); 2227 if (!type->isBooleanType() && type->isIntegerType() && 2228 !(type->isUnsignedIntegerType() && 2229 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) && 2230 CGF.getLangOpts().getSignedOverflowBehavior() != 2231 LangOptions::SOB_Trapping) { 2232 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP; 2233 switch (OpInfo.Opcode) { 2234 // We don't have atomicrmw operands for *, %, /, <<, >> 2235 case BO_MulAssign: case BO_DivAssign: 2236 case BO_RemAssign: 2237 case BO_ShlAssign: 2238 case BO_ShrAssign: 2239 break; 2240 case BO_AddAssign: 2241 aop = llvm::AtomicRMWInst::Add; 2242 break; 2243 case BO_SubAssign: 2244 aop = llvm::AtomicRMWInst::Sub; 2245 break; 2246 case BO_AndAssign: 2247 aop = llvm::AtomicRMWInst::And; 2248 break; 2249 case BO_XorAssign: 2250 aop = llvm::AtomicRMWInst::Xor; 2251 break; 2252 case BO_OrAssign: 2253 aop = llvm::AtomicRMWInst::Or; 2254 break; 2255 default: 2256 llvm_unreachable("Invalid compound assignment type"); 2257 } 2258 if (aop != llvm::AtomicRMWInst::BAD_BINOP) { 2259 llvm::Value *amt = CGF.EmitToMemory( 2260 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy, 2261 E->getExprLoc()), 2262 LHSTy); 2263 Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt, 2264 llvm::AtomicOrdering::SequentiallyConsistent); 2265 return LHSLV; 2266 } 2267 } 2268 // FIXME: For floating point types, we should be saving and restoring the 2269 // floating point environment in the loop. 2270 llvm::BasicBlock *startBB = Builder.GetInsertBlock(); 2271 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn); 2272 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 2273 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type); 2274 Builder.CreateBr(opBB); 2275 Builder.SetInsertPoint(opBB); 2276 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2); 2277 atomicPHI->addIncoming(OpInfo.LHS, startBB); 2278 OpInfo.LHS = atomicPHI; 2279 } 2280 else 2281 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc()); 2282 2283 SourceLocation Loc = E->getExprLoc(); 2284 OpInfo.LHS = 2285 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc); 2286 2287 // Expand the binary operator. 2288 Result = (this->*Func)(OpInfo); 2289 2290 // Convert the result back to the LHS type. 2291 Result = 2292 EmitScalarConversion(Result, E->getComputationResultType(), LHSTy, Loc); 2293 2294 if (atomicPHI) { 2295 llvm::BasicBlock *opBB = Builder.GetInsertBlock(); 2296 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn); 2297 auto Pair = CGF.EmitAtomicCompareExchange( 2298 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc()); 2299 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy); 2300 llvm::Value *success = Pair.second; 2301 atomicPHI->addIncoming(old, opBB); 2302 Builder.CreateCondBr(success, contBB, opBB); 2303 Builder.SetInsertPoint(contBB); 2304 return LHSLV; 2305 } 2306 2307 // Store the result value into the LHS lvalue. Bit-fields are handled 2308 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 2309 // 'An assignment expression has the value of the left operand after the 2310 // assignment...'. 2311 if (LHSLV.isBitField()) 2312 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result); 2313 else 2314 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV); 2315 2316 return LHSLV; 2317 } 2318 2319 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 2320 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 2321 bool Ignore = TestAndClearIgnoreResultAssign(); 2322 Value *RHS; 2323 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS); 2324 2325 // If the result is clearly ignored, return now. 2326 if (Ignore) 2327 return nullptr; 2328 2329 // The result of an assignment in C is the assigned r-value. 2330 if (!CGF.getLangOpts().CPlusPlus) 2331 return RHS; 2332 2333 // If the lvalue is non-volatile, return the computed value of the assignment. 2334 if (!LHS.isVolatileQualified()) 2335 return RHS; 2336 2337 // Otherwise, reload the value. 2338 return EmitLoadOfLValue(LHS, E->getExprLoc()); 2339 } 2340 2341 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck( 2342 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) { 2343 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks; 2344 2345 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) { 2346 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero), 2347 SanitizerKind::IntegerDivideByZero)); 2348 } 2349 2350 const auto *BO = cast<BinaryOperator>(Ops.E); 2351 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) && 2352 Ops.Ty->hasSignedIntegerRepresentation() && 2353 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS())) { 2354 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType()); 2355 2356 llvm::Value *IntMin = 2357 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth())); 2358 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL); 2359 2360 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin); 2361 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne); 2362 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or"); 2363 Checks.push_back( 2364 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow)); 2365 } 2366 2367 if (Checks.size() > 0) 2368 EmitBinOpCheck(Checks, Ops); 2369 } 2370 2371 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 2372 { 2373 CodeGenFunction::SanitizerScope SanScope(&CGF); 2374 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 2375 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 2376 Ops.Ty->isIntegerType()) { 2377 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 2378 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true); 2379 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) && 2380 Ops.Ty->isRealFloatingType()) { 2381 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 2382 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero); 2383 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero), 2384 Ops); 2385 } 2386 } 2387 2388 if (Ops.LHS->getType()->isFPOrFPVectorTy()) { 2389 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 2390 if (CGF.getLangOpts().OpenCL && 2391 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) { 2392 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp 2393 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 2394 // build option allows an application to specify that single precision 2395 // floating-point divide (x/y and 1/x) and sqrt used in the program 2396 // source are correctly rounded. 2397 llvm::Type *ValTy = Val->getType(); 2398 if (ValTy->isFloatTy() || 2399 (isa<llvm::VectorType>(ValTy) && 2400 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy())) 2401 CGF.SetFPAccuracy(Val, 2.5); 2402 } 2403 return Val; 2404 } 2405 else if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2406 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 2407 else 2408 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 2409 } 2410 2411 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 2412 // Rem in C can't be a floating point type: C99 6.5.5p2. 2413 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) || 2414 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) && 2415 Ops.Ty->isIntegerType()) { 2416 CodeGenFunction::SanitizerScope SanScope(&CGF); 2417 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty)); 2418 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false); 2419 } 2420 2421 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2422 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 2423 else 2424 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 2425 } 2426 2427 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 2428 unsigned IID; 2429 unsigned OpID = 0; 2430 2431 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType(); 2432 switch (Ops.Opcode) { 2433 case BO_Add: 2434 case BO_AddAssign: 2435 OpID = 1; 2436 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow : 2437 llvm::Intrinsic::uadd_with_overflow; 2438 break; 2439 case BO_Sub: 2440 case BO_SubAssign: 2441 OpID = 2; 2442 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow : 2443 llvm::Intrinsic::usub_with_overflow; 2444 break; 2445 case BO_Mul: 2446 case BO_MulAssign: 2447 OpID = 3; 2448 IID = isSigned ? llvm::Intrinsic::smul_with_overflow : 2449 llvm::Intrinsic::umul_with_overflow; 2450 break; 2451 default: 2452 llvm_unreachable("Unsupported operation for overflow detection"); 2453 } 2454 OpID <<= 1; 2455 if (isSigned) 2456 OpID |= 1; 2457 2458 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 2459 2460 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); 2461 2462 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS}); 2463 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 2464 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 2465 2466 // Handle overflow with llvm.trap if no custom handler has been specified. 2467 const std::string *handlerName = 2468 &CGF.getLangOpts().OverflowHandler; 2469 if (handlerName->empty()) { 2470 // If the signed-integer-overflow sanitizer is enabled, emit a call to its 2471 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap. 2472 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { 2473 CodeGenFunction::SanitizerScope SanScope(&CGF); 2474 llvm::Value *NotOverflow = Builder.CreateNot(overflow); 2475 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow 2476 : SanitizerKind::UnsignedIntegerOverflow; 2477 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops); 2478 } else 2479 CGF.EmitTrapCheck(Builder.CreateNot(overflow)); 2480 return result; 2481 } 2482 2483 // Branch in case of overflow. 2484 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 2485 llvm::BasicBlock *continueBB = 2486 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode()); 2487 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn); 2488 2489 Builder.CreateCondBr(overflow, overflowBB, continueBB); 2490 2491 // If an overflow handler is set, then we want to call it and then use its 2492 // result, if it returns. 2493 Builder.SetInsertPoint(overflowBB); 2494 2495 // Get the overflow handler. 2496 llvm::Type *Int8Ty = CGF.Int8Ty; 2497 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty }; 2498 llvm::FunctionType *handlerTy = 2499 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true); 2500 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName); 2501 2502 // Sign extend the args to 64-bit, so that we can use the same handler for 2503 // all types of overflow. 2504 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty); 2505 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty); 2506 2507 // Call the handler with the two arguments, the operation, and the size of 2508 // the result. 2509 llvm::Value *handlerArgs[] = { 2510 lhs, 2511 rhs, 2512 Builder.getInt8(OpID), 2513 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()) 2514 }; 2515 llvm::Value *handlerResult = 2516 CGF.EmitNounwindRuntimeCall(handler, handlerArgs); 2517 2518 // Truncate the result back to the desired size. 2519 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 2520 Builder.CreateBr(continueBB); 2521 2522 Builder.SetInsertPoint(continueBB); 2523 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2); 2524 phi->addIncoming(result, initialBB); 2525 phi->addIncoming(handlerResult, overflowBB); 2526 2527 return phi; 2528 } 2529 2530 /// Emit pointer + index arithmetic. 2531 static Value *emitPointerArithmetic(CodeGenFunction &CGF, 2532 const BinOpInfo &op, 2533 bool isSubtraction) { 2534 // Must have binary (not unary) expr here. Unary pointer 2535 // increment/decrement doesn't use this path. 2536 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2537 2538 Value *pointer = op.LHS; 2539 Expr *pointerOperand = expr->getLHS(); 2540 Value *index = op.RHS; 2541 Expr *indexOperand = expr->getRHS(); 2542 2543 // In a subtraction, the LHS is always the pointer. 2544 if (!isSubtraction && !pointer->getType()->isPointerTy()) { 2545 std::swap(pointer, index); 2546 std::swap(pointerOperand, indexOperand); 2547 } 2548 2549 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth(); 2550 auto &DL = CGF.CGM.getDataLayout(); 2551 auto PtrTy = cast<llvm::PointerType>(pointer->getType()); 2552 if (width != DL.getTypeSizeInBits(PtrTy)) { 2553 // Zero-extend or sign-extend the pointer value according to 2554 // whether the index is signed or not. 2555 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType(); 2556 index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned, 2557 "idx.ext"); 2558 } 2559 2560 // If this is subtraction, negate the index. 2561 if (isSubtraction) 2562 index = CGF.Builder.CreateNeg(index, "idx.neg"); 2563 2564 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds)) 2565 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(), 2566 /*Accessed*/ false); 2567 2568 const PointerType *pointerType 2569 = pointerOperand->getType()->getAs<PointerType>(); 2570 if (!pointerType) { 2571 QualType objectType = pointerOperand->getType() 2572 ->castAs<ObjCObjectPointerType>() 2573 ->getPointeeType(); 2574 llvm::Value *objectSize 2575 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType)); 2576 2577 index = CGF.Builder.CreateMul(index, objectSize); 2578 2579 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 2580 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 2581 return CGF.Builder.CreateBitCast(result, pointer->getType()); 2582 } 2583 2584 QualType elementType = pointerType->getPointeeType(); 2585 if (const VariableArrayType *vla 2586 = CGF.getContext().getAsVariableArrayType(elementType)) { 2587 // The element count here is the total number of non-VLA elements. 2588 llvm::Value *numElements = CGF.getVLASize(vla).first; 2589 2590 // Effectively, the multiply by the VLA size is part of the GEP. 2591 // GEP indexes are signed, and scaling an index isn't permitted to 2592 // signed-overflow, so we use the same semantics for our explicit 2593 // multiply. We suppress this if overflow is not undefined behavior. 2594 if (CGF.getLangOpts().isSignedOverflowDefined()) { 2595 index = CGF.Builder.CreateMul(index, numElements, "vla.index"); 2596 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 2597 } else { 2598 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index"); 2599 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2600 } 2601 return pointer; 2602 } 2603 2604 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 2605 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 2606 // future proof. 2607 if (elementType->isVoidType() || elementType->isFunctionType()) { 2608 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy); 2609 result = CGF.Builder.CreateGEP(result, index, "add.ptr"); 2610 return CGF.Builder.CreateBitCast(result, pointer->getType()); 2611 } 2612 2613 if (CGF.getLangOpts().isSignedOverflowDefined()) 2614 return CGF.Builder.CreateGEP(pointer, index, "add.ptr"); 2615 2616 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr"); 2617 } 2618 2619 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and 2620 // Addend. Use negMul and negAdd to negate the first operand of the Mul or 2621 // the add operand respectively. This allows fmuladd to represent a*b-c, or 2622 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to 2623 // efficient operations. 2624 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend, 2625 const CodeGenFunction &CGF, CGBuilderTy &Builder, 2626 bool negMul, bool negAdd) { 2627 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set."); 2628 2629 Value *MulOp0 = MulOp->getOperand(0); 2630 Value *MulOp1 = MulOp->getOperand(1); 2631 if (negMul) { 2632 MulOp0 = 2633 Builder.CreateFSub( 2634 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0, 2635 "neg"); 2636 } else if (negAdd) { 2637 Addend = 2638 Builder.CreateFSub( 2639 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend, 2640 "neg"); 2641 } 2642 2643 Value *FMulAdd = Builder.CreateCall( 2644 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()), 2645 {MulOp0, MulOp1, Addend}); 2646 MulOp->eraseFromParent(); 2647 2648 return FMulAdd; 2649 } 2650 2651 // Check whether it would be legal to emit an fmuladd intrinsic call to 2652 // represent op and if so, build the fmuladd. 2653 // 2654 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on. 2655 // Does NOT check the type of the operation - it's assumed that this function 2656 // will be called from contexts where it's known that the type is contractable. 2657 static Value* tryEmitFMulAdd(const BinOpInfo &op, 2658 const CodeGenFunction &CGF, CGBuilderTy &Builder, 2659 bool isSub=false) { 2660 2661 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign || 2662 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) && 2663 "Only fadd/fsub can be the root of an fmuladd."); 2664 2665 // Check whether this op is marked as fusable. 2666 if (!op.FPContractable) 2667 return nullptr; 2668 2669 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is 2670 // either disabled, or handled entirely by the LLVM backend). 2671 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On) 2672 return nullptr; 2673 2674 // We have a potentially fusable op. Look for a mul on one of the operands. 2675 // Also, make sure that the mul result isn't used directly. In that case, 2676 // there's no point creating a muladd operation. 2677 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) { 2678 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul && 2679 LHSBinOp->use_empty()) 2680 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub); 2681 } 2682 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) { 2683 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul && 2684 RHSBinOp->use_empty()) 2685 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false); 2686 } 2687 2688 return nullptr; 2689 } 2690 2691 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) { 2692 if (op.LHS->getType()->isPointerTy() || 2693 op.RHS->getType()->isPointerTy()) 2694 return emitPointerArithmetic(CGF, op, /*subtraction*/ false); 2695 2696 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2697 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2698 case LangOptions::SOB_Defined: 2699 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2700 case LangOptions::SOB_Undefined: 2701 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2702 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 2703 // Fall through. 2704 case LangOptions::SOB_Trapping: 2705 if (CanElideOverflowCheck(CGF.getContext(), op)) 2706 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add"); 2707 return EmitOverflowCheckedBinOp(op); 2708 } 2709 } 2710 2711 if (op.Ty->isUnsignedIntegerType() && 2712 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 2713 !CanElideOverflowCheck(CGF.getContext(), op)) 2714 return EmitOverflowCheckedBinOp(op); 2715 2716 if (op.LHS->getType()->isFPOrFPVectorTy()) { 2717 // Try to form an fmuladd. 2718 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder)) 2719 return FMulAdd; 2720 2721 return Builder.CreateFAdd(op.LHS, op.RHS, "add"); 2722 } 2723 2724 return Builder.CreateAdd(op.LHS, op.RHS, "add"); 2725 } 2726 2727 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) { 2728 // The LHS is always a pointer if either side is. 2729 if (!op.LHS->getType()->isPointerTy()) { 2730 if (op.Ty->isSignedIntegerOrEnumerationType()) { 2731 switch (CGF.getLangOpts().getSignedOverflowBehavior()) { 2732 case LangOptions::SOB_Defined: 2733 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2734 case LangOptions::SOB_Undefined: 2735 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) 2736 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 2737 // Fall through. 2738 case LangOptions::SOB_Trapping: 2739 if (CanElideOverflowCheck(CGF.getContext(), op)) 2740 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub"); 2741 return EmitOverflowCheckedBinOp(op); 2742 } 2743 } 2744 2745 if (op.Ty->isUnsignedIntegerType() && 2746 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) && 2747 !CanElideOverflowCheck(CGF.getContext(), op)) 2748 return EmitOverflowCheckedBinOp(op); 2749 2750 if (op.LHS->getType()->isFPOrFPVectorTy()) { 2751 // Try to form an fmuladd. 2752 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true)) 2753 return FMulAdd; 2754 return Builder.CreateFSub(op.LHS, op.RHS, "sub"); 2755 } 2756 2757 return Builder.CreateSub(op.LHS, op.RHS, "sub"); 2758 } 2759 2760 // If the RHS is not a pointer, then we have normal pointer 2761 // arithmetic. 2762 if (!op.RHS->getType()->isPointerTy()) 2763 return emitPointerArithmetic(CGF, op, /*subtraction*/ true); 2764 2765 // Otherwise, this is a pointer subtraction. 2766 2767 // Do the raw subtraction part. 2768 llvm::Value *LHS 2769 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast"); 2770 llvm::Value *RHS 2771 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast"); 2772 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 2773 2774 // Okay, figure out the element size. 2775 const BinaryOperator *expr = cast<BinaryOperator>(op.E); 2776 QualType elementType = expr->getLHS()->getType()->getPointeeType(); 2777 2778 llvm::Value *divisor = nullptr; 2779 2780 // For a variable-length array, this is going to be non-constant. 2781 if (const VariableArrayType *vla 2782 = CGF.getContext().getAsVariableArrayType(elementType)) { 2783 llvm::Value *numElements; 2784 std::tie(numElements, elementType) = CGF.getVLASize(vla); 2785 2786 divisor = numElements; 2787 2788 // Scale the number of non-VLA elements by the non-VLA element size. 2789 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType); 2790 if (!eltSize.isOne()) 2791 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor); 2792 2793 // For everything elese, we can just compute it, safe in the 2794 // assumption that Sema won't let anything through that we can't 2795 // safely compute the size of. 2796 } else { 2797 CharUnits elementSize; 2798 // Handle GCC extension for pointer arithmetic on void* and 2799 // function pointer types. 2800 if (elementType->isVoidType() || elementType->isFunctionType()) 2801 elementSize = CharUnits::One(); 2802 else 2803 elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2804 2805 // Don't even emit the divide for element size of 1. 2806 if (elementSize.isOne()) 2807 return diffInChars; 2808 2809 divisor = CGF.CGM.getSize(elementSize); 2810 } 2811 2812 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 2813 // pointer difference in C is only defined in the case where both operands 2814 // are pointing to elements of an array. 2815 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div"); 2816 } 2817 2818 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) { 2819 llvm::IntegerType *Ty; 2820 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType())) 2821 Ty = cast<llvm::IntegerType>(VT->getElementType()); 2822 else 2823 Ty = cast<llvm::IntegerType>(LHS->getType()); 2824 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1); 2825 } 2826 2827 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 2828 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2829 // RHS to the same size as the LHS. 2830 Value *RHS = Ops.RHS; 2831 if (Ops.LHS->getType() != RHS->getType()) 2832 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2833 2834 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) && 2835 Ops.Ty->hasSignedIntegerRepresentation() && 2836 !CGF.getLangOpts().isSignedOverflowDefined(); 2837 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent); 2838 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2839 if (CGF.getLangOpts().OpenCL) 2840 RHS = 2841 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask"); 2842 else if ((SanitizeBase || SanitizeExponent) && 2843 isa<llvm::IntegerType>(Ops.LHS->getType())) { 2844 CodeGenFunction::SanitizerScope SanScope(&CGF); 2845 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks; 2846 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS); 2847 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne); 2848 2849 if (SanitizeExponent) { 2850 Checks.push_back( 2851 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent)); 2852 } 2853 2854 if (SanitizeBase) { 2855 // Check whether we are shifting any non-zero bits off the top of the 2856 // integer. We only emit this check if exponent is valid - otherwise 2857 // instructions below will have undefined behavior themselves. 2858 llvm::BasicBlock *Orig = Builder.GetInsertBlock(); 2859 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 2860 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check"); 2861 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont); 2862 llvm::Value *PromotedWidthMinusOne = 2863 (RHS == Ops.RHS) ? WidthMinusOne 2864 : GetWidthMinusOneValue(Ops.LHS, RHS); 2865 CGF.EmitBlock(CheckShiftBase); 2866 llvm::Value *BitsShiftedOff = Builder.CreateLShr( 2867 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros", 2868 /*NUW*/ true, /*NSW*/ true), 2869 "shl.check"); 2870 if (CGF.getLangOpts().CPlusPlus) { 2871 // In C99, we are not permitted to shift a 1 bit into the sign bit. 2872 // Under C++11's rules, shifting a 1 bit into the sign bit is 2873 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't 2874 // define signed left shifts, so we use the C99 and C++11 rules there). 2875 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1); 2876 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One); 2877 } 2878 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0); 2879 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero); 2880 CGF.EmitBlock(Cont); 2881 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2); 2882 BaseCheck->addIncoming(Builder.getTrue(), Orig); 2883 BaseCheck->addIncoming(ValidBase, CheckShiftBase); 2884 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase)); 2885 } 2886 2887 assert(!Checks.empty()); 2888 EmitBinOpCheck(Checks, Ops); 2889 } 2890 2891 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 2892 } 2893 2894 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 2895 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 2896 // RHS to the same size as the LHS. 2897 Value *RHS = Ops.RHS; 2898 if (Ops.LHS->getType() != RHS->getType()) 2899 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 2900 2901 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2902 if (CGF.getLangOpts().OpenCL) 2903 RHS = 2904 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask"); 2905 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) && 2906 isa<llvm::IntegerType>(Ops.LHS->getType())) { 2907 CodeGenFunction::SanitizerScope SanScope(&CGF); 2908 llvm::Value *Valid = 2909 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)); 2910 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops); 2911 } 2912 2913 if (Ops.Ty->hasUnsignedIntegerRepresentation()) 2914 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 2915 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 2916 } 2917 2918 enum IntrinsicType { VCMPEQ, VCMPGT }; 2919 // return corresponding comparison intrinsic for given vector type 2920 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, 2921 BuiltinType::Kind ElemKind) { 2922 switch (ElemKind) { 2923 default: llvm_unreachable("unexpected element type"); 2924 case BuiltinType::Char_U: 2925 case BuiltinType::UChar: 2926 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2927 llvm::Intrinsic::ppc_altivec_vcmpgtub_p; 2928 case BuiltinType::Char_S: 2929 case BuiltinType::SChar: 2930 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p : 2931 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p; 2932 case BuiltinType::UShort: 2933 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2934 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p; 2935 case BuiltinType::Short: 2936 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p : 2937 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p; 2938 case BuiltinType::UInt: 2939 case BuiltinType::ULong: 2940 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2941 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p; 2942 case BuiltinType::Int: 2943 case BuiltinType::Long: 2944 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p : 2945 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p; 2946 case BuiltinType::Float: 2947 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p : 2948 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p; 2949 } 2950 } 2951 2952 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E, 2953 llvm::CmpInst::Predicate UICmpOpc, 2954 llvm::CmpInst::Predicate SICmpOpc, 2955 llvm::CmpInst::Predicate FCmpOpc) { 2956 TestAndClearIgnoreResultAssign(); 2957 Value *Result; 2958 QualType LHSTy = E->getLHS()->getType(); 2959 QualType RHSTy = E->getRHS()->getType(); 2960 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) { 2961 assert(E->getOpcode() == BO_EQ || 2962 E->getOpcode() == BO_NE); 2963 Value *LHS = CGF.EmitScalarExpr(E->getLHS()); 2964 Value *RHS = CGF.EmitScalarExpr(E->getRHS()); 2965 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison( 2966 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE); 2967 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) { 2968 Value *LHS = Visit(E->getLHS()); 2969 Value *RHS = Visit(E->getRHS()); 2970 2971 // If AltiVec, the comparison results in a numeric type, so we use 2972 // intrinsics comparing vectors and giving 0 or 1 as a result 2973 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) { 2974 // constants for mapping CR6 register bits to predicate result 2975 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6; 2976 2977 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic; 2978 2979 // in several cases vector arguments order will be reversed 2980 Value *FirstVecArg = LHS, 2981 *SecondVecArg = RHS; 2982 2983 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType(); 2984 const BuiltinType *BTy = ElTy->getAs<BuiltinType>(); 2985 BuiltinType::Kind ElementKind = BTy->getKind(); 2986 2987 switch(E->getOpcode()) { 2988 default: llvm_unreachable("is not a comparison operation"); 2989 case BO_EQ: 2990 CR6 = CR6_LT; 2991 ID = GetIntrinsic(VCMPEQ, ElementKind); 2992 break; 2993 case BO_NE: 2994 CR6 = CR6_EQ; 2995 ID = GetIntrinsic(VCMPEQ, ElementKind); 2996 break; 2997 case BO_LT: 2998 CR6 = CR6_LT; 2999 ID = GetIntrinsic(VCMPGT, ElementKind); 3000 std::swap(FirstVecArg, SecondVecArg); 3001 break; 3002 case BO_GT: 3003 CR6 = CR6_LT; 3004 ID = GetIntrinsic(VCMPGT, ElementKind); 3005 break; 3006 case BO_LE: 3007 if (ElementKind == BuiltinType::Float) { 3008 CR6 = CR6_LT; 3009 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 3010 std::swap(FirstVecArg, SecondVecArg); 3011 } 3012 else { 3013 CR6 = CR6_EQ; 3014 ID = GetIntrinsic(VCMPGT, ElementKind); 3015 } 3016 break; 3017 case BO_GE: 3018 if (ElementKind == BuiltinType::Float) { 3019 CR6 = CR6_LT; 3020 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p; 3021 } 3022 else { 3023 CR6 = CR6_EQ; 3024 ID = GetIntrinsic(VCMPGT, ElementKind); 3025 std::swap(FirstVecArg, SecondVecArg); 3026 } 3027 break; 3028 } 3029 3030 Value *CR6Param = Builder.getInt32(CR6); 3031 llvm::Function *F = CGF.CGM.getIntrinsic(ID); 3032 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg}); 3033 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 3034 E->getExprLoc()); 3035 } 3036 3037 if (LHS->getType()->isFPOrFPVectorTy()) { 3038 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp"); 3039 } else if (LHSTy->hasSignedIntegerRepresentation()) { 3040 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp"); 3041 } else { 3042 // Unsigned integers and pointers. 3043 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp"); 3044 } 3045 3046 // If this is a vector comparison, sign extend the result to the appropriate 3047 // vector integer type and return it (don't convert to bool). 3048 if (LHSTy->isVectorType()) 3049 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 3050 3051 } else { 3052 // Complex Comparison: can only be an equality comparison. 3053 CodeGenFunction::ComplexPairTy LHS, RHS; 3054 QualType CETy; 3055 if (auto *CTy = LHSTy->getAs<ComplexType>()) { 3056 LHS = CGF.EmitComplexExpr(E->getLHS()); 3057 CETy = CTy->getElementType(); 3058 } else { 3059 LHS.first = Visit(E->getLHS()); 3060 LHS.second = llvm::Constant::getNullValue(LHS.first->getType()); 3061 CETy = LHSTy; 3062 } 3063 if (auto *CTy = RHSTy->getAs<ComplexType>()) { 3064 RHS = CGF.EmitComplexExpr(E->getRHS()); 3065 assert(CGF.getContext().hasSameUnqualifiedType(CETy, 3066 CTy->getElementType()) && 3067 "The element types must always match."); 3068 (void)CTy; 3069 } else { 3070 RHS.first = Visit(E->getRHS()); 3071 RHS.second = llvm::Constant::getNullValue(RHS.first->getType()); 3072 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) && 3073 "The element types must always match."); 3074 } 3075 3076 Value *ResultR, *ResultI; 3077 if (CETy->isRealFloatingType()) { 3078 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r"); 3079 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i"); 3080 } else { 3081 // Complex comparisons can only be equality comparisons. As such, signed 3082 // and unsigned opcodes are the same. 3083 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r"); 3084 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i"); 3085 } 3086 3087 if (E->getOpcode() == BO_EQ) { 3088 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 3089 } else { 3090 assert(E->getOpcode() == BO_NE && 3091 "Complex comparison other than == or != ?"); 3092 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 3093 } 3094 } 3095 3096 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(), 3097 E->getExprLoc()); 3098 } 3099 3100 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 3101 bool Ignore = TestAndClearIgnoreResultAssign(); 3102 3103 Value *RHS; 3104 LValue LHS; 3105 3106 switch (E->getLHS()->getType().getObjCLifetime()) { 3107 case Qualifiers::OCL_Strong: 3108 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore); 3109 break; 3110 3111 case Qualifiers::OCL_Autoreleasing: 3112 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E); 3113 break; 3114 3115 case Qualifiers::OCL_ExplicitNone: 3116 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore); 3117 break; 3118 3119 case Qualifiers::OCL_Weak: 3120 RHS = Visit(E->getRHS()); 3121 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 3122 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore); 3123 break; 3124 3125 case Qualifiers::OCL_None: 3126 // __block variables need to have the rhs evaluated first, plus 3127 // this should improve codegen just a little. 3128 RHS = Visit(E->getRHS()); 3129 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 3130 3131 // Store the value into the LHS. Bit-fields are handled specially 3132 // because the result is altered by the store, i.e., [C99 6.5.16p1] 3133 // 'An assignment expression has the value of the left operand after 3134 // the assignment...'. 3135 if (LHS.isBitField()) { 3136 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS); 3137 } else { 3138 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc()); 3139 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS); 3140 } 3141 } 3142 3143 // If the result is clearly ignored, return now. 3144 if (Ignore) 3145 return nullptr; 3146 3147 // The result of an assignment in C is the assigned r-value. 3148 if (!CGF.getLangOpts().CPlusPlus) 3149 return RHS; 3150 3151 // If the lvalue is non-volatile, return the computed value of the assignment. 3152 if (!LHS.isVolatileQualified()) 3153 return RHS; 3154 3155 // Otherwise, reload the value. 3156 return EmitLoadOfLValue(LHS, E->getExprLoc()); 3157 } 3158 3159 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 3160 // Perform vector logical and on comparisons with zero vectors. 3161 if (E->getType()->isVectorType()) { 3162 CGF.incrementProfileCounter(E); 3163 3164 Value *LHS = Visit(E->getLHS()); 3165 Value *RHS = Visit(E->getRHS()); 3166 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 3167 if (LHS->getType()->isFPOrFPVectorTy()) { 3168 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 3169 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 3170 } else { 3171 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 3172 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 3173 } 3174 Value *And = Builder.CreateAnd(LHS, RHS); 3175 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext"); 3176 } 3177 3178 llvm::Type *ResTy = ConvertType(E->getType()); 3179 3180 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 3181 // If we have 1 && X, just emit X without inserting the control flow. 3182 bool LHSCondVal; 3183 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 3184 if (LHSCondVal) { // If we have 1 && X, just emit X. 3185 CGF.incrementProfileCounter(E); 3186 3187 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3188 // ZExt result to int or bool. 3189 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext"); 3190 } 3191 3192 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false. 3193 if (!CGF.ContainsLabel(E->getRHS())) 3194 return llvm::Constant::getNullValue(ResTy); 3195 } 3196 3197 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 3198 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 3199 3200 CodeGenFunction::ConditionalEvaluation eval(CGF); 3201 3202 // Branch on the LHS first. If it is false, go to the failure (cont) block. 3203 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, 3204 CGF.getProfileCount(E->getRHS())); 3205 3206 // Any edges into the ContBlock are now from an (indeterminate number of) 3207 // edges from this first condition. All of these values will be false. Start 3208 // setting up the PHI node in the Cont Block for this. 3209 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 3210 "", ContBlock); 3211 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 3212 PI != PE; ++PI) 3213 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 3214 3215 eval.begin(CGF); 3216 CGF.EmitBlock(RHSBlock); 3217 CGF.incrementProfileCounter(E); 3218 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3219 eval.end(CGF); 3220 3221 // Reaquire the RHS block, as there may be subblocks inserted. 3222 RHSBlock = Builder.GetInsertBlock(); 3223 3224 // Emit an unconditional branch from this block to ContBlock. 3225 { 3226 // There is no need to emit line number for unconditional branch. 3227 auto NL = ApplyDebugLocation::CreateEmpty(CGF); 3228 CGF.EmitBlock(ContBlock); 3229 } 3230 // Insert an entry into the phi node for the edge with the value of RHSCond. 3231 PN->addIncoming(RHSCond, RHSBlock); 3232 3233 // ZExt result to int. 3234 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext"); 3235 } 3236 3237 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 3238 // Perform vector logical or on comparisons with zero vectors. 3239 if (E->getType()->isVectorType()) { 3240 CGF.incrementProfileCounter(E); 3241 3242 Value *LHS = Visit(E->getLHS()); 3243 Value *RHS = Visit(E->getRHS()); 3244 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType()); 3245 if (LHS->getType()->isFPOrFPVectorTy()) { 3246 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp"); 3247 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp"); 3248 } else { 3249 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp"); 3250 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp"); 3251 } 3252 Value *Or = Builder.CreateOr(LHS, RHS); 3253 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext"); 3254 } 3255 3256 llvm::Type *ResTy = ConvertType(E->getType()); 3257 3258 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 3259 // If we have 0 || X, just emit X without inserting the control flow. 3260 bool LHSCondVal; 3261 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) { 3262 if (!LHSCondVal) { // If we have 0 || X, just emit X. 3263 CGF.incrementProfileCounter(E); 3264 3265 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3266 // ZExt result to int or bool. 3267 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext"); 3268 } 3269 3270 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true. 3271 if (!CGF.ContainsLabel(E->getRHS())) 3272 return llvm::ConstantInt::get(ResTy, 1); 3273 } 3274 3275 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 3276 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 3277 3278 CodeGenFunction::ConditionalEvaluation eval(CGF); 3279 3280 // Branch on the LHS first. If it is true, go to the success (cont) block. 3281 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock, 3282 CGF.getCurrentProfileCount() - 3283 CGF.getProfileCount(E->getRHS())); 3284 3285 // Any edges into the ContBlock are now from an (indeterminate number of) 3286 // edges from this first condition. All of these values will be true. Start 3287 // setting up the PHI node in the Cont Block for this. 3288 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2, 3289 "", ContBlock); 3290 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 3291 PI != PE; ++PI) 3292 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 3293 3294 eval.begin(CGF); 3295 3296 // Emit the RHS condition as a bool value. 3297 CGF.EmitBlock(RHSBlock); 3298 CGF.incrementProfileCounter(E); 3299 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 3300 3301 eval.end(CGF); 3302 3303 // Reaquire the RHS block, as there may be subblocks inserted. 3304 RHSBlock = Builder.GetInsertBlock(); 3305 3306 // Emit an unconditional branch from this block to ContBlock. Insert an entry 3307 // into the phi node for the edge with the value of RHSCond. 3308 CGF.EmitBlock(ContBlock); 3309 PN->addIncoming(RHSCond, RHSBlock); 3310 3311 // ZExt result to int. 3312 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext"); 3313 } 3314 3315 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 3316 CGF.EmitIgnoredExpr(E->getLHS()); 3317 CGF.EnsureInsertPoint(); 3318 return Visit(E->getRHS()); 3319 } 3320 3321 //===----------------------------------------------------------------------===// 3322 // Other Operators 3323 //===----------------------------------------------------------------------===// 3324 3325 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 3326 /// expression is cheap enough and side-effect-free enough to evaluate 3327 /// unconditionally instead of conditionally. This is used to convert control 3328 /// flow into selects in some cases. 3329 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, 3330 CodeGenFunction &CGF) { 3331 // Anything that is an integer or floating point constant is fine. 3332 return E->IgnoreParens()->isEvaluatable(CGF.getContext()); 3333 3334 // Even non-volatile automatic variables can't be evaluated unconditionally. 3335 // Referencing a thread_local may cause non-trivial initialization work to 3336 // occur. If we're inside a lambda and one of the variables is from the scope 3337 // outside the lambda, that function may have returned already. Reading its 3338 // locals is a bad idea. Also, these reads may introduce races there didn't 3339 // exist in the source-level program. 3340 } 3341 3342 3343 Value *ScalarExprEmitter:: 3344 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 3345 TestAndClearIgnoreResultAssign(); 3346 3347 // Bind the common expression if necessary. 3348 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 3349 3350 Expr *condExpr = E->getCond(); 3351 Expr *lhsExpr = E->getTrueExpr(); 3352 Expr *rhsExpr = E->getFalseExpr(); 3353 3354 // If the condition constant folds and can be elided, try to avoid emitting 3355 // the condition and the dead arm. 3356 bool CondExprBool; 3357 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 3358 Expr *live = lhsExpr, *dead = rhsExpr; 3359 if (!CondExprBool) std::swap(live, dead); 3360 3361 // If the dead side doesn't have labels we need, just emit the Live part. 3362 if (!CGF.ContainsLabel(dead)) { 3363 if (CondExprBool) 3364 CGF.incrementProfileCounter(E); 3365 Value *Result = Visit(live); 3366 3367 // If the live part is a throw expression, it acts like it has a void 3368 // type, so evaluating it returns a null Value*. However, a conditional 3369 // with non-void type must return a non-null Value*. 3370 if (!Result && !E->getType()->isVoidType()) 3371 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType())); 3372 3373 return Result; 3374 } 3375 } 3376 3377 // OpenCL: If the condition is a vector, we can treat this condition like 3378 // the select function. 3379 if (CGF.getLangOpts().OpenCL 3380 && condExpr->getType()->isVectorType()) { 3381 CGF.incrementProfileCounter(E); 3382 3383 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr); 3384 llvm::Value *LHS = Visit(lhsExpr); 3385 llvm::Value *RHS = Visit(rhsExpr); 3386 3387 llvm::Type *condType = ConvertType(condExpr->getType()); 3388 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType); 3389 3390 unsigned numElem = vecTy->getNumElements(); 3391 llvm::Type *elemType = vecTy->getElementType(); 3392 3393 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy); 3394 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec); 3395 llvm::Value *tmp = Builder.CreateSExt(TestMSB, 3396 llvm::VectorType::get(elemType, 3397 numElem), 3398 "sext"); 3399 llvm::Value *tmp2 = Builder.CreateNot(tmp); 3400 3401 // Cast float to int to perform ANDs if necessary. 3402 llvm::Value *RHSTmp = RHS; 3403 llvm::Value *LHSTmp = LHS; 3404 bool wasCast = false; 3405 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType()); 3406 if (rhsVTy->getElementType()->isFloatingPointTy()) { 3407 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType()); 3408 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType()); 3409 wasCast = true; 3410 } 3411 3412 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2); 3413 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp); 3414 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond"); 3415 if (wasCast) 3416 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType()); 3417 3418 return tmp5; 3419 } 3420 3421 // If this is a really simple expression (like x ? 4 : 5), emit this as a 3422 // select instead of as control flow. We can only do this if it is cheap and 3423 // safe to evaluate the LHS and RHS unconditionally. 3424 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) && 3425 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) { 3426 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr); 3427 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty); 3428 3429 CGF.incrementProfileCounter(E, StepV); 3430 3431 llvm::Value *LHS = Visit(lhsExpr); 3432 llvm::Value *RHS = Visit(rhsExpr); 3433 if (!LHS) { 3434 // If the conditional has void type, make sure we return a null Value*. 3435 assert(!RHS && "LHS and RHS types must match"); 3436 return nullptr; 3437 } 3438 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 3439 } 3440 3441 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 3442 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 3443 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 3444 3445 CodeGenFunction::ConditionalEvaluation eval(CGF); 3446 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, 3447 CGF.getProfileCount(lhsExpr)); 3448 3449 CGF.EmitBlock(LHSBlock); 3450 CGF.incrementProfileCounter(E); 3451 eval.begin(CGF); 3452 Value *LHS = Visit(lhsExpr); 3453 eval.end(CGF); 3454 3455 LHSBlock = Builder.GetInsertBlock(); 3456 Builder.CreateBr(ContBlock); 3457 3458 CGF.EmitBlock(RHSBlock); 3459 eval.begin(CGF); 3460 Value *RHS = Visit(rhsExpr); 3461 eval.end(CGF); 3462 3463 RHSBlock = Builder.GetInsertBlock(); 3464 CGF.EmitBlock(ContBlock); 3465 3466 // If the LHS or RHS is a throw expression, it will be legitimately null. 3467 if (!LHS) 3468 return RHS; 3469 if (!RHS) 3470 return LHS; 3471 3472 // Create a PHI node for the real part. 3473 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond"); 3474 PN->addIncoming(LHS, LHSBlock); 3475 PN->addIncoming(RHS, RHSBlock); 3476 return PN; 3477 } 3478 3479 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 3480 return Visit(E->getChosenSubExpr()); 3481 } 3482 3483 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 3484 QualType Ty = VE->getType(); 3485 3486 if (Ty->isVariablyModifiedType()) 3487 CGF.EmitVariablyModifiedType(Ty); 3488 3489 Address ArgValue = Address::invalid(); 3490 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 3491 3492 llvm::Type *ArgTy = ConvertType(VE->getType()); 3493 3494 // If EmitVAArg fails, emit an error. 3495 if (!ArgPtr.isValid()) { 3496 CGF.ErrorUnsupported(VE, "va_arg expression"); 3497 return llvm::UndefValue::get(ArgTy); 3498 } 3499 3500 // FIXME Volatility. 3501 llvm::Value *Val = Builder.CreateLoad(ArgPtr); 3502 3503 // If EmitVAArg promoted the type, we must truncate it. 3504 if (ArgTy != Val->getType()) { 3505 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy()) 3506 Val = Builder.CreateIntToPtr(Val, ArgTy); 3507 else 3508 Val = Builder.CreateTrunc(Val, ArgTy); 3509 } 3510 3511 return Val; 3512 } 3513 3514 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) { 3515 return CGF.EmitBlockLiteral(block); 3516 } 3517 3518 // Convert a vec3 to vec4, or vice versa. 3519 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, 3520 Value *Src, unsigned NumElementsDst) { 3521 llvm::Value *UnV = llvm::UndefValue::get(Src->getType()); 3522 SmallVector<llvm::Constant*, 4> Args; 3523 Args.push_back(Builder.getInt32(0)); 3524 Args.push_back(Builder.getInt32(1)); 3525 Args.push_back(Builder.getInt32(2)); 3526 if (NumElementsDst == 4) 3527 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty)); 3528 llvm::Constant *Mask = llvm::ConstantVector::get(Args); 3529 return Builder.CreateShuffleVector(Src, UnV, Mask); 3530 } 3531 3532 // Create cast instructions for converting LLVM value \p Src to LLVM type \p 3533 // DstTy. \p Src has the same size as \p DstTy. Both are single value types 3534 // but could be scalar or vectors of different lengths, and either can be 3535 // pointer. 3536 // There are 4 cases: 3537 // 1. non-pointer -> non-pointer : needs 1 bitcast 3538 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast 3539 // 3. pointer -> non-pointer 3540 // a) pointer -> intptr_t : needs 1 ptrtoint 3541 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast 3542 // 4. non-pointer -> pointer 3543 // a) intptr_t -> pointer : needs 1 inttoptr 3544 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr 3545 // Note: for cases 3b and 4b two casts are required since LLVM casts do not 3546 // allow casting directly between pointer types and non-integer non-pointer 3547 // types. 3548 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder, 3549 const llvm::DataLayout &DL, 3550 Value *Src, llvm::Type *DstTy, 3551 StringRef Name = "") { 3552 auto SrcTy = Src->getType(); 3553 3554 // Case 1. 3555 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy()) 3556 return Builder.CreateBitCast(Src, DstTy, Name); 3557 3558 // Case 2. 3559 if (SrcTy->isPointerTy() && DstTy->isPointerTy()) 3560 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name); 3561 3562 // Case 3. 3563 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) { 3564 // Case 3b. 3565 if (!DstTy->isIntegerTy()) 3566 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy)); 3567 // Cases 3a and 3b. 3568 return Builder.CreateBitOrPointerCast(Src, DstTy, Name); 3569 } 3570 3571 // Case 4b. 3572 if (!SrcTy->isIntegerTy()) 3573 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy)); 3574 // Cases 4a and 4b. 3575 return Builder.CreateIntToPtr(Src, DstTy, Name); 3576 } 3577 3578 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) { 3579 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr()); 3580 llvm::Type *DstTy = ConvertType(E->getType()); 3581 3582 llvm::Type *SrcTy = Src->getType(); 3583 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ? 3584 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0; 3585 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ? 3586 cast<llvm::VectorType>(DstTy)->getNumElements() : 0; 3587 3588 // Going from vec3 to non-vec3 is a special case and requires a shuffle 3589 // vector to get a vec4, then a bitcast if the target type is different. 3590 if (NumElementsSrc == 3 && NumElementsDst != 3) { 3591 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4); 3592 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 3593 DstTy); 3594 Src->setName("astype"); 3595 return Src; 3596 } 3597 3598 // Going from non-vec3 to vec3 is a special case and requires a bitcast 3599 // to vec4 if the original type is not vec4, then a shuffle vector to 3600 // get a vec3. 3601 if (NumElementsSrc != 3 && NumElementsDst == 3) { 3602 auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4); 3603 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src, 3604 Vec4Ty); 3605 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3); 3606 Src->setName("astype"); 3607 return Src; 3608 } 3609 3610 return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), 3611 Src, DstTy, "astype"); 3612 } 3613 3614 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) { 3615 return CGF.EmitAtomicExpr(E).getScalarVal(); 3616 } 3617 3618 //===----------------------------------------------------------------------===// 3619 // Entry Point into this File 3620 //===----------------------------------------------------------------------===// 3621 3622 /// Emit the computation of the specified expression of scalar type, ignoring 3623 /// the result. 3624 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 3625 assert(E && hasScalarEvaluationKind(E->getType()) && 3626 "Invalid scalar expression to emit"); 3627 3628 return ScalarExprEmitter(*this, IgnoreResultAssign) 3629 .Visit(const_cast<Expr *>(E)); 3630 } 3631 3632 /// Emit a conversion from the specified type to the specified destination type, 3633 /// both of which are LLVM scalar types. 3634 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 3635 QualType DstTy, 3636 SourceLocation Loc) { 3637 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) && 3638 "Invalid scalar expression to emit"); 3639 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc); 3640 } 3641 3642 /// Emit a conversion from the specified complex type to the specified 3643 /// destination type, where the destination type is an LLVM scalar type. 3644 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 3645 QualType SrcTy, 3646 QualType DstTy, 3647 SourceLocation Loc) { 3648 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) && 3649 "Invalid complex -> scalar conversion"); 3650 return ScalarExprEmitter(*this) 3651 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc); 3652 } 3653 3654 3655 llvm::Value *CodeGenFunction:: 3656 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 3657 bool isInc, bool isPre) { 3658 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre); 3659 } 3660 3661 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) { 3662 // object->isa or (*object).isa 3663 // Generate code as for: *(Class*)object 3664 3665 Expr *BaseExpr = E->getBase(); 3666 Address Addr = Address::invalid(); 3667 if (BaseExpr->isRValue()) { 3668 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign()); 3669 } else { 3670 Addr = EmitLValue(BaseExpr).getAddress(); 3671 } 3672 3673 // Cast the address to Class*. 3674 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType())); 3675 return MakeAddrLValue(Addr, E->getType()); 3676 } 3677 3678 3679 LValue CodeGenFunction::EmitCompoundAssignmentLValue( 3680 const CompoundAssignOperator *E) { 3681 ScalarExprEmitter Scalar(*this); 3682 Value *Result = nullptr; 3683 switch (E->getOpcode()) { 3684 #define COMPOUND_OP(Op) \ 3685 case BO_##Op##Assign: \ 3686 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \ 3687 Result) 3688 COMPOUND_OP(Mul); 3689 COMPOUND_OP(Div); 3690 COMPOUND_OP(Rem); 3691 COMPOUND_OP(Add); 3692 COMPOUND_OP(Sub); 3693 COMPOUND_OP(Shl); 3694 COMPOUND_OP(Shr); 3695 COMPOUND_OP(And); 3696 COMPOUND_OP(Xor); 3697 COMPOUND_OP(Or); 3698 #undef COMPOUND_OP 3699 3700 case BO_PtrMemD: 3701 case BO_PtrMemI: 3702 case BO_Mul: 3703 case BO_Div: 3704 case BO_Rem: 3705 case BO_Add: 3706 case BO_Sub: 3707 case BO_Shl: 3708 case BO_Shr: 3709 case BO_LT: 3710 case BO_GT: 3711 case BO_LE: 3712 case BO_GE: 3713 case BO_EQ: 3714 case BO_NE: 3715 case BO_And: 3716 case BO_Xor: 3717 case BO_Or: 3718 case BO_LAnd: 3719 case BO_LOr: 3720 case BO_Assign: 3721 case BO_Comma: 3722 llvm_unreachable("Not valid compound assignment operators"); 3723 } 3724 3725 llvm_unreachable("Unhandled compound assignment operator"); 3726 } 3727