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