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