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