CGExprScalar.cpp revision 191dfe909d6cc18e9134ac23ac4daaedeceb862f
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CodeGenModule.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/RecordLayout.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Basic/TargetInfo.h" 21#include "llvm/Constants.h" 22#include "llvm/Function.h" 23#include "llvm/GlobalVariable.h" 24#include "llvm/Intrinsics.h" 25#include "llvm/Module.h" 26#include "llvm/Support/Compiler.h" 27#include "llvm/Support/CFG.h" 28#include "llvm/Target/TargetData.h" 29#include <cstdarg> 30 31using namespace clang; 32using namespace CodeGen; 33using llvm::Value; 34 35//===----------------------------------------------------------------------===// 36// Scalar Expression Emitter 37//===----------------------------------------------------------------------===// 38 39struct BinOpInfo { 40 Value *LHS; 41 Value *RHS; 42 QualType Ty; // Computation Type. 43 const BinaryOperator *E; 44}; 45 46namespace { 47class VISIBILITY_HIDDEN ScalarExprEmitter 48 : public StmtVisitor<ScalarExprEmitter, Value*> { 49 CodeGenFunction &CGF; 50 CGBuilderTy &Builder; 51 bool IgnoreResultAssign; 52 llvm::LLVMContext &VMContext; 53public: 54 55 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false) 56 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira), 57 VMContext(cgf.getLLVMContext()) { 58 } 59 60 //===--------------------------------------------------------------------===// 61 // Utilities 62 //===--------------------------------------------------------------------===// 63 64 bool TestAndClearIgnoreResultAssign() { 65 bool I = IgnoreResultAssign; 66 IgnoreResultAssign = false; 67 return I; 68 } 69 70 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 71 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 72 73 Value *EmitLoadOfLValue(LValue LV, QualType T) { 74 return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 75 } 76 77 /// EmitLoadOfLValue - Given an expression with complex type that represents a 78 /// value l-value, this method emits the address of the l-value, then loads 79 /// and returns the result. 80 Value *EmitLoadOfLValue(const Expr *E) { 81 return EmitLoadOfLValue(EmitLValue(E), E->getType()); 82 } 83 84 /// EmitConversionToBool - Convert the specified expression value to a 85 /// boolean (i1) truth value. This is equivalent to "Val != 0". 86 Value *EmitConversionToBool(Value *Src, QualType DstTy); 87 88 /// EmitScalarConversion - Emit a conversion from the specified type to the 89 /// specified destination type, both of which are LLVM scalar types. 90 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 91 92 /// EmitComplexToScalarConversion - Emit a conversion from the specified 93 /// complex type to the specified destination type, where the destination type 94 /// is an LLVM scalar type. 95 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 96 QualType SrcTy, QualType DstTy); 97 98 //===--------------------------------------------------------------------===// 99 // Visitor Methods 100 //===--------------------------------------------------------------------===// 101 102 Value *VisitStmt(Stmt *S) { 103 S->dump(CGF.getContext().getSourceManager()); 104 assert(0 && "Stmt can't have complex result type!"); 105 return 0; 106 } 107 Value *VisitExpr(Expr *S); 108 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 109 110 // Leaves. 111 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 112 return llvm::ConstantInt::get(VMContext, E->getValue()); 113 } 114 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 115 return llvm::ConstantFP::get(VMContext, E->getValue()); 116 } 117 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 119 } 120 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 121 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 122 } 123 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 124 return llvm::Constant::getNullValue(ConvertType(E->getType())); 125 } 126 Value *VisitGNUNullExpr(const GNUNullExpr *E) { 127 return llvm::Constant::getNullValue(ConvertType(E->getType())); 128 } 129 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 130 return llvm::ConstantInt::get(ConvertType(E->getType()), 131 CGF.getContext().typesAreCompatible( 132 E->getArgType1(), E->getArgType2())); 133 } 134 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 135 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 136 llvm::Value *V = 137 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), 138 CGF.GetIDForAddrOfLabel(E->getLabel())); 139 140 return Builder.CreateIntToPtr(V, ConvertType(E->getType())); 141 } 142 143 // l-values. 144 Value *VisitDeclRefExpr(DeclRefExpr *E) { 145 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl())) 146 return llvm::ConstantInt::get(VMContext, EC->getInitVal()); 147 return EmitLoadOfLValue(E); 148 } 149 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 150 return CGF.EmitObjCSelectorExpr(E); 151 } 152 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 153 return CGF.EmitObjCProtocolExpr(E); 154 } 155 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 156 return EmitLoadOfLValue(E); 157 } 158 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 159 return EmitLoadOfLValue(E); 160 } 161 Value *VisitObjCImplicitSetterGetterRefExpr( 162 ObjCImplicitSetterGetterRefExpr *E) { 163 return EmitLoadOfLValue(E); 164 } 165 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 166 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 167 } 168 169 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 170 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 171 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); } 172 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 173 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 174 return EmitLoadOfLValue(E); 175 } 176 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); } 177 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 178 return EmitLValue(E).getAddress(); 179 } 180 181 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); } 182 183 Value *VisitInitListExpr(InitListExpr *E) { 184 bool Ignore = TestAndClearIgnoreResultAssign(); 185 (void)Ignore; 186 assert (Ignore == false && "init list ignored"); 187 unsigned NumInitElements = E->getNumInits(); 188 189 if (E->hadArrayRangeDesignator()) { 190 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 191 } 192 193 const llvm::VectorType *VType = 194 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 195 196 // We have a scalar in braces. Just use the first element. 197 if (!VType) 198 return Visit(E->getInit(0)); 199 200 unsigned NumVectorElements = VType->getNumElements(); 201 const llvm::Type *ElementType = VType->getElementType(); 202 203 // Emit individual vector element stores. 204 llvm::Value *V = llvm::UndefValue::get(VType); 205 206 // Emit initializers 207 unsigned i; 208 for (i = 0; i < NumInitElements; ++i) { 209 Value *NewV = Visit(E->getInit(i)); 210 Value *Idx = 211 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i); 212 V = Builder.CreateInsertElement(V, NewV, Idx); 213 } 214 215 // Emit remaining default initializers 216 for (/* Do not initialize i*/; i < NumVectorElements; ++i) { 217 Value *Idx = 218 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i); 219 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType); 220 V = Builder.CreateInsertElement(V, NewV, Idx); 221 } 222 223 return V; 224 } 225 226 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 227 return llvm::Constant::getNullValue(ConvertType(E->getType())); 228 } 229 Value *VisitCastExpr(const CastExpr *E) { 230 // Make sure to evaluate VLA bounds now so that we have them for later. 231 if (E->getType()->isVariablyModifiedType()) 232 CGF.EmitVLASize(E->getType()); 233 234 return EmitCastExpr(E->getSubExpr(), E->getType(), E->getCastKind()); 235 } 236 Value *EmitCastExpr(const Expr *E, QualType T, CastExpr::CastKind Kind); 237 238 Value *VisitCallExpr(const CallExpr *E) { 239 if (E->getCallReturnType()->isReferenceType()) 240 return EmitLoadOfLValue(E); 241 242 return CGF.EmitCallExpr(E).getScalarVal(); 243 } 244 245 Value *VisitStmtExpr(const StmtExpr *E); 246 247 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E); 248 249 // Unary Operators. 250 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre); 251 Value *VisitUnaryPostDec(const UnaryOperator *E) { 252 return VisitPrePostIncDec(E, false, false); 253 } 254 Value *VisitUnaryPostInc(const UnaryOperator *E) { 255 return VisitPrePostIncDec(E, true, false); 256 } 257 Value *VisitUnaryPreDec(const UnaryOperator *E) { 258 return VisitPrePostIncDec(E, false, true); 259 } 260 Value *VisitUnaryPreInc(const UnaryOperator *E) { 261 return VisitPrePostIncDec(E, true, true); 262 } 263 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 264 return EmitLValue(E->getSubExpr()).getAddress(); 265 } 266 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 267 Value *VisitUnaryPlus(const UnaryOperator *E) { 268 // This differs from gcc, though, most likely due to a bug in gcc. 269 TestAndClearIgnoreResultAssign(); 270 return Visit(E->getSubExpr()); 271 } 272 Value *VisitUnaryMinus (const UnaryOperator *E); 273 Value *VisitUnaryNot (const UnaryOperator *E); 274 Value *VisitUnaryLNot (const UnaryOperator *E); 275 Value *VisitUnaryReal (const UnaryOperator *E); 276 Value *VisitUnaryImag (const UnaryOperator *E); 277 Value *VisitUnaryExtension(const UnaryOperator *E) { 278 return Visit(E->getSubExpr()); 279 } 280 Value *VisitUnaryOffsetOf(const UnaryOperator *E); 281 282 // C++ 283 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 284 return Visit(DAE->getExpr()); 285 } 286 Value *VisitCXXThisExpr(CXXThisExpr *TE) { 287 return CGF.LoadCXXThis(); 288 } 289 290 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 291 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal(); 292 } 293 Value *VisitCXXNewExpr(const CXXNewExpr *E) { 294 return CGF.EmitCXXNewExpr(E); 295 } 296 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 297 CGF.EmitCXXDeleteExpr(E); 298 return 0; 299 } 300 301 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) { 302 // C++ [expr.pseudo]p1: 303 // The result shall only be used as the operand for the function call 304 // operator (), and the result of such a call has type void. The only 305 // effect is the evaluation of the postfix-expression before the dot or 306 // arrow. 307 CGF.EmitScalarExpr(E->getBase()); 308 return 0; 309 } 310 311 // Binary Operators. 312 Value *EmitMul(const BinOpInfo &Ops) { 313 if (CGF.getContext().getLangOptions().OverflowChecking 314 && Ops.Ty->isSignedIntegerType()) 315 return EmitOverflowCheckedBinOp(Ops); 316 if (Ops.LHS->getType()->isFPOrFPVector()) 317 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul"); 318 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 319 } 320 /// Create a binary op that checks for overflow. 321 /// Currently only supports +, - and *. 322 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops); 323 Value *EmitDiv(const BinOpInfo &Ops); 324 Value *EmitRem(const BinOpInfo &Ops); 325 Value *EmitAdd(const BinOpInfo &Ops); 326 Value *EmitSub(const BinOpInfo &Ops); 327 Value *EmitShl(const BinOpInfo &Ops); 328 Value *EmitShr(const BinOpInfo &Ops); 329 Value *EmitAnd(const BinOpInfo &Ops) { 330 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 331 } 332 Value *EmitXor(const BinOpInfo &Ops) { 333 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 334 } 335 Value *EmitOr (const BinOpInfo &Ops) { 336 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 337 } 338 339 BinOpInfo EmitBinOps(const BinaryOperator *E); 340 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 341 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 342 343 // Binary operators and binary compound assignment operators. 344#define HANDLEBINOP(OP) \ 345 Value *VisitBin ## OP(const BinaryOperator *E) { \ 346 return Emit ## OP(EmitBinOps(E)); \ 347 } \ 348 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 349 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 350 } 351 HANDLEBINOP(Mul); 352 HANDLEBINOP(Div); 353 HANDLEBINOP(Rem); 354 HANDLEBINOP(Add); 355 HANDLEBINOP(Sub); 356 HANDLEBINOP(Shl); 357 HANDLEBINOP(Shr); 358 HANDLEBINOP(And); 359 HANDLEBINOP(Xor); 360 HANDLEBINOP(Or); 361#undef HANDLEBINOP 362 363 // Comparisons. 364 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 365 unsigned SICmpOpc, unsigned FCmpOpc); 366#define VISITCOMP(CODE, UI, SI, FP) \ 367 Value *VisitBin##CODE(const BinaryOperator *E) { \ 368 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 369 llvm::FCmpInst::FP); } 370 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT); 371 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT); 372 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE); 373 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE); 374 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ); 375 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE); 376#undef VISITCOMP 377 378 Value *VisitBinAssign (const BinaryOperator *E); 379 380 Value *VisitBinLAnd (const BinaryOperator *E); 381 Value *VisitBinLOr (const BinaryOperator *E); 382 Value *VisitBinComma (const BinaryOperator *E); 383 384 // Other Operators. 385 Value *VisitBlockExpr(const BlockExpr *BE); 386 Value *VisitConditionalOperator(const ConditionalOperator *CO); 387 Value *VisitChooseExpr(ChooseExpr *CE); 388 Value *VisitVAArgExpr(VAArgExpr *VE); 389 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 390 return CGF.EmitObjCStringLiteral(E); 391 } 392}; 393} // end anonymous namespace. 394 395//===----------------------------------------------------------------------===// 396// Utilities 397//===----------------------------------------------------------------------===// 398 399/// EmitConversionToBool - Convert the specified expression value to a 400/// boolean (i1) truth value. This is equivalent to "Val != 0". 401Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 402 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs"); 403 404 if (SrcType->isRealFloatingType()) { 405 // Compare against 0.0 for fp scalars. 406 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 407 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 408 } 409 410 if (SrcType->isMemberPointerType()) { 411 // FIXME: This is ABI specific. 412 413 // Compare against -1. 414 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType()); 415 return Builder.CreateICmpNE(Src, NegativeOne, "tobool"); 416 } 417 418 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 419 "Unknown scalar type to convert"); 420 421 // Because of the type rules of C, we often end up computing a logical value, 422 // then zero extending it to int, then wanting it as a logical value again. 423 // Optimize this common case. 424 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 425 if (ZI->getOperand(0)->getType() == 426 llvm::Type::getInt1Ty(CGF.getLLVMContext())) { 427 Value *Result = ZI->getOperand(0); 428 // If there aren't any more uses, zap the instruction to save space. 429 // Note that there can be more uses, for example if this 430 // is the result of an assignment. 431 if (ZI->use_empty()) 432 ZI->eraseFromParent(); 433 return Result; 434 } 435 } 436 437 // Compare against an integer or pointer null. 438 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 439 return Builder.CreateICmpNE(Src, Zero, "tobool"); 440} 441 442/// EmitScalarConversion - Emit a conversion from the specified type to the 443/// specified destination type, both of which are LLVM scalar types. 444Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 445 QualType DstType) { 446 SrcType = CGF.getContext().getCanonicalType(SrcType); 447 DstType = CGF.getContext().getCanonicalType(DstType); 448 if (SrcType == DstType) return Src; 449 450 if (DstType->isVoidType()) return 0; 451 452 llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 453 454 // Handle conversions to bool first, they are special: comparisons against 0. 455 if (DstType->isBooleanType()) 456 return EmitConversionToBool(Src, SrcType); 457 458 const llvm::Type *DstTy = ConvertType(DstType); 459 460 // Ignore conversions like int -> uint. 461 if (Src->getType() == DstTy) 462 return Src; 463 464 // Handle pointer conversions next: pointers can only be converted to/from 465 // other pointers and integers. Check for pointer types in terms of LLVM, as 466 // some native types (like Obj-C id) may map to a pointer type. 467 if (isa<llvm::PointerType>(DstTy)) { 468 // The source value may be an integer, or a pointer. 469 if (isa<llvm::PointerType>(Src->getType())) 470 return Builder.CreateBitCast(Src, DstTy, "conv"); 471 472 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 473 // First, convert to the correct width so that we control the kind of 474 // extension. 475 const llvm::Type *MiddleTy = 476 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 477 bool InputSigned = SrcType->isSignedIntegerType(); 478 llvm::Value* IntResult = 479 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv"); 480 // Then, cast to pointer. 481 return Builder.CreateIntToPtr(IntResult, DstTy, "conv"); 482 } 483 484 if (isa<llvm::PointerType>(Src->getType())) { 485 // Must be an ptr to int cast. 486 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 487 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 488 } 489 490 // A scalar can be splatted to an extended vector of the same element type 491 if (DstType->isExtVectorType() && !SrcType->isVectorType()) { 492 // Cast the scalar to element type 493 QualType EltTy = DstType->getAsExtVectorType()->getElementType(); 494 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy); 495 496 // Insert the element in element zero of an undef vector 497 llvm::Value *UnV = llvm::UndefValue::get(DstTy); 498 llvm::Value *Idx = 499 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 500 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp"); 501 502 // Splat the element across to all elements 503 llvm::SmallVector<llvm::Constant*, 16> Args; 504 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements(); 505 for (unsigned i = 0; i < NumElements; i++) 506 Args.push_back(llvm::ConstantInt::get( 507 llvm::Type::getInt32Ty(VMContext), 0)); 508 509 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 510 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat"); 511 return Yay; 512 } 513 514 // Allow bitcast from vector to integer/fp of the same size. 515 if (isa<llvm::VectorType>(Src->getType()) || 516 isa<llvm::VectorType>(DstTy)) 517 return Builder.CreateBitCast(Src, DstTy, "conv"); 518 519 // Finally, we have the arithmetic types: real int/float. 520 if (isa<llvm::IntegerType>(Src->getType())) { 521 bool InputSigned = SrcType->isSignedIntegerType(); 522 if (isa<llvm::IntegerType>(DstTy)) 523 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 524 else if (InputSigned) 525 return Builder.CreateSIToFP(Src, DstTy, "conv"); 526 else 527 return Builder.CreateUIToFP(Src, DstTy, "conv"); 528 } 529 530 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion"); 531 if (isa<llvm::IntegerType>(DstTy)) { 532 if (DstType->isSignedIntegerType()) 533 return Builder.CreateFPToSI(Src, DstTy, "conv"); 534 else 535 return Builder.CreateFPToUI(Src, DstTy, "conv"); 536 } 537 538 assert(DstTy->isFloatingPoint() && "Unknown real conversion"); 539 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 540 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 541 else 542 return Builder.CreateFPExt(Src, DstTy, "conv"); 543} 544 545/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 546/// type to the specified destination type, where the destination type is an 547/// LLVM scalar type. 548Value *ScalarExprEmitter:: 549EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 550 QualType SrcTy, QualType DstTy) { 551 // Get the source element type. 552 SrcTy = SrcTy->getAsComplexType()->getElementType(); 553 554 // Handle conversions to bool first, they are special: comparisons against 0. 555 if (DstTy->isBooleanType()) { 556 // Complex != 0 -> (Real != 0) | (Imag != 0) 557 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 558 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 559 return Builder.CreateOr(Src.first, Src.second, "tobool"); 560 } 561 562 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 563 // the imaginary part of the complex value is discarded and the value of the 564 // real part is converted according to the conversion rules for the 565 // corresponding real type. 566 return EmitScalarConversion(Src.first, SrcTy, DstTy); 567} 568 569 570//===----------------------------------------------------------------------===// 571// Visitor Methods 572//===----------------------------------------------------------------------===// 573 574Value *ScalarExprEmitter::VisitExpr(Expr *E) { 575 CGF.ErrorUnsupported(E, "scalar expression"); 576 if (E->getType()->isVoidType()) 577 return 0; 578 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 579} 580 581Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 582 llvm::SmallVector<llvm::Constant*, 32> indices; 583 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 584 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 585 } 586 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 587 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 588 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 589 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 590} 591 592Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 593 TestAndClearIgnoreResultAssign(); 594 595 // Emit subscript expressions in rvalue context's. For most cases, this just 596 // loads the lvalue formed by the subscript expr. However, we have to be 597 // careful, because the base of a vector subscript is occasionally an rvalue, 598 // so we can't get it as an lvalue. 599 if (!E->getBase()->getType()->isVectorType()) 600 return EmitLoadOfLValue(E); 601 602 // Handle the vector case. The base must be a vector, the index must be an 603 // integer value. 604 Value *Base = Visit(E->getBase()); 605 Value *Idx = Visit(E->getIdx()); 606 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType(); 607 Idx = Builder.CreateIntCast(Idx, 608 llvm::Type::getInt32Ty(CGF.getLLVMContext()), 609 IdxSigned, 610 "vecidxcast"); 611 return Builder.CreateExtractElement(Base, Idx, "vecext"); 612} 613 614// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 615// have to handle a more broad range of conversions than explicit casts, as they 616// handle things like function to ptr-to-function decay etc. 617Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy, 618 CastExpr::CastKind Kind) { 619 if (!DestTy->isVoidType()) 620 TestAndClearIgnoreResultAssign(); 621 622 switch (Kind) { 623 default: 624 break; 625 case CastExpr::CK_BitCast: { 626 Value *Src = Visit(const_cast<Expr*>(E)); 627 return Builder.CreateBitCast(Src, ConvertType(DestTy)); 628 } 629 case CastExpr::CK_ArrayToPointerDecay: { 630 assert(E->getType()->isArrayType() && 631 "Array to pointer decay must have array source type!"); 632 633 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays. 634 635 // Note that VLA pointers are always decayed, so we don't need to do 636 // anything here. 637 if (!E->getType()->isVariableArrayType()) { 638 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer"); 639 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 640 ->getElementType()) && 641 "Expected pointer to array"); 642 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 643 } 644 645 // The resultant pointer type can be implicitly casted to other pointer 646 // types as well (e.g. void*) and can be implicitly converted to integer. 647 const llvm::Type *DestLTy = ConvertType(DestTy); 648 if (V->getType() != DestLTy) { 649 if (isa<llvm::PointerType>(DestLTy)) 650 V = Builder.CreateBitCast(V, DestLTy, "ptrconv"); 651 else { 652 assert(isa<llvm::IntegerType>(DestLTy) && "Unknown array decay"); 653 V = Builder.CreatePtrToInt(V, DestLTy, "ptrconv"); 654 } 655 } 656 return V; 657 } 658 case CastExpr::CK_NullToMemberPointer: 659 return CGF.CGM.EmitNullConstant(DestTy); 660 661 case CastExpr::CK_DerivedToBase: { 662 const RecordType *DerivedClassTy = 663 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 664 CXXRecordDecl *DerivedClassDecl = 665 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 666 667 const RecordType *BaseClassTy = 668 DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>(); 669 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl()); 670 671 Value *Src = Visit(const_cast<Expr*>(E)); 672 return CGF.GetAddressCXXOfBaseClass(Src, DerivedClassDecl, BaseClassDecl, 673 /*NullCheckValue=*/true); 674 } 675 676 } 677 678 // Handle cases where the source is an non-complex type. 679 680 if (!CGF.hasAggregateLLVMType(E->getType())) { 681 Value *Src = Visit(const_cast<Expr*>(E)); 682 683 // Use EmitScalarConversion to perform the conversion. 684 return EmitScalarConversion(Src, E->getType(), DestTy); 685 } 686 687 if (E->getType()->isAnyComplexType()) { 688 // Handle cases where the source is a complex type. 689 bool IgnoreImag = true; 690 bool IgnoreImagAssign = true; 691 bool IgnoreReal = IgnoreResultAssign; 692 bool IgnoreRealAssign = IgnoreResultAssign; 693 if (DestTy->isBooleanType()) 694 IgnoreImagAssign = IgnoreImag = false; 695 else if (DestTy->isVoidType()) { 696 IgnoreReal = IgnoreImag = false; 697 IgnoreRealAssign = IgnoreImagAssign = true; 698 } 699 CodeGenFunction::ComplexPairTy V 700 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign, 701 IgnoreImagAssign); 702 return EmitComplexToScalarConversion(V, E->getType(), DestTy); 703 } 704 705 // Okay, this is a cast from an aggregate. It must be a cast to void. Just 706 // evaluate the result and return. 707 CGF.EmitAggExpr(E, 0, false, true); 708 return 0; 709} 710 711Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 712 return CGF.EmitCompoundStmt(*E->getSubStmt(), 713 !E->getType()->isVoidType()).getScalarVal(); 714} 715 716Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 717 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp"); 718} 719 720//===----------------------------------------------------------------------===// 721// Unary Operators 722//===----------------------------------------------------------------------===// 723 724Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E, 725 bool isInc, bool isPre) { 726 LValue LV = EmitLValue(E->getSubExpr()); 727 QualType ValTy = E->getSubExpr()->getType(); 728 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal(); 729 730 llvm::LLVMContext &VMContext = CGF.getLLVMContext(); 731 732 int AmountVal = isInc ? 1 : -1; 733 734 if (ValTy->isPointerType() && 735 ValTy->getAs<PointerType>()->isVariableArrayType()) { 736 // The amount of the addition/subtraction needs to account for the VLA size 737 CGF.ErrorUnsupported(E, "VLA pointer inc/dec"); 738 } 739 740 Value *NextVal; 741 if (const llvm::PointerType *PT = 742 dyn_cast<llvm::PointerType>(InVal->getType())) { 743 llvm::Constant *Inc = 744 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal); 745 if (!isa<llvm::FunctionType>(PT->getElementType())) { 746 QualType PTEE = ValTy->getPointeeType(); 747 if (const ObjCInterfaceType *OIT = 748 dyn_cast<ObjCInterfaceType>(PTEE)) { 749 // Handle interface types, which are not represented with a concrete type. 750 int size = CGF.getContext().getTypeSize(OIT) / 8; 751 if (!isInc) 752 size = -size; 753 Inc = llvm::ConstantInt::get(Inc->getType(), size); 754 const llvm::Type *i8Ty = 755 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 756 InVal = Builder.CreateBitCast(InVal, i8Ty); 757 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr"); 758 llvm::Value *lhs = LV.getAddress(); 759 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty)); 760 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(), 761 CGF.getContext().getObjCGCAttrKind(ValTy)); 762 } else 763 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec"); 764 } else { 765 const llvm::Type *i8Ty = 766 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 767 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp"); 768 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec"); 769 NextVal = Builder.CreateBitCast(NextVal, InVal->getType()); 770 } 771 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) { 772 // Bool++ is an interesting case, due to promotion rules, we get: 773 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 -> 774 // Bool = ((int)Bool+1) != 0 775 // An interesting aspect of this is that increment is always true. 776 // Decrement does not have this property. 777 NextVal = llvm::ConstantInt::getTrue(VMContext); 778 } else if (isa<llvm::IntegerType>(InVal->getType())) { 779 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal); 780 781 // Signed integer overflow is undefined behavior. 782 if (ValTy->isSignedIntegerType()) 783 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec"); 784 else 785 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 786 } else { 787 // Add the inc/dec to the real part. 788 if (InVal->getType() == llvm::Type::getFloatTy(VMContext)) 789 NextVal = 790 llvm::ConstantFP::get(VMContext, 791 llvm::APFloat(static_cast<float>(AmountVal))); 792 else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext)) 793 NextVal = 794 llvm::ConstantFP::get(VMContext, 795 llvm::APFloat(static_cast<double>(AmountVal))); 796 else { 797 llvm::APFloat F(static_cast<float>(AmountVal)); 798 bool ignored; 799 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 800 &ignored); 801 NextVal = llvm::ConstantFP::get(VMContext, F); 802 } 803 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec"); 804 } 805 806 // Store the updated result through the lvalue. 807 if (LV.isBitfield()) 808 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, 809 &NextVal); 810 else 811 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy); 812 813 // If this is a postinc, return the value read from memory, otherwise use the 814 // updated value. 815 return isPre ? NextVal : InVal; 816} 817 818 819Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 820 TestAndClearIgnoreResultAssign(); 821 Value *Op = Visit(E->getSubExpr()); 822 if (Op->getType()->isFPOrFPVector()) 823 return Builder.CreateFNeg(Op, "neg"); 824 return Builder.CreateNeg(Op, "neg"); 825} 826 827Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 828 TestAndClearIgnoreResultAssign(); 829 Value *Op = Visit(E->getSubExpr()); 830 return Builder.CreateNot(Op, "neg"); 831} 832 833Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 834 // Compare operand to zero. 835 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 836 837 // Invert value. 838 // TODO: Could dynamically modify easy computations here. For example, if 839 // the operand is an icmp ne, turn into icmp eq. 840 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 841 842 // ZExt result to the expr type. 843 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext"); 844} 845 846/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 847/// argument of the sizeof expression as an integer. 848Value * 849ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 850 QualType TypeToSize = E->getTypeOfArgument(); 851 if (E->isSizeOf()) { 852 if (const VariableArrayType *VAT = 853 CGF.getContext().getAsVariableArrayType(TypeToSize)) { 854 if (E->isArgumentType()) { 855 // sizeof(type) - make sure to emit the VLA size. 856 CGF.EmitVLASize(TypeToSize); 857 } else { 858 // C99 6.5.3.4p2: If the argument is an expression of type 859 // VLA, it is evaluated. 860 CGF.EmitAnyExpr(E->getArgumentExpr()); 861 } 862 863 return CGF.GetVLASize(VAT); 864 } 865 } 866 867 // If this isn't sizeof(vla), the result must be constant; use the constant 868 // folding logic so we don't have to duplicate it here. 869 Expr::EvalResult Result; 870 E->Evaluate(Result, CGF.getContext()); 871 return llvm::ConstantInt::get(VMContext, Result.Val.getInt()); 872} 873 874Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 875 Expr *Op = E->getSubExpr(); 876 if (Op->getType()->isAnyComplexType()) 877 return CGF.EmitComplexExpr(Op, false, true, false, true).first; 878 return Visit(Op); 879} 880Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 881 Expr *Op = E->getSubExpr(); 882 if (Op->getType()->isAnyComplexType()) 883 return CGF.EmitComplexExpr(Op, true, false, true, false).second; 884 885 // __imag on a scalar returns zero. Emit the subexpr to ensure side 886 // effects are evaluated, but not the actual value. 887 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) 888 CGF.EmitLValue(Op); 889 else 890 CGF.EmitScalarExpr(Op, true); 891 return llvm::Constant::getNullValue(ConvertType(E->getType())); 892} 893 894Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) { 895 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress(); 896 const llvm::Type* ResultType = ConvertType(E->getType()); 897 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof"); 898} 899 900//===----------------------------------------------------------------------===// 901// Binary Operators 902//===----------------------------------------------------------------------===// 903 904BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 905 TestAndClearIgnoreResultAssign(); 906 BinOpInfo Result; 907 Result.LHS = Visit(E->getLHS()); 908 Result.RHS = Visit(E->getRHS()); 909 Result.Ty = E->getType(); 910 Result.E = E; 911 return Result; 912} 913 914Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 915 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 916 bool Ignore = TestAndClearIgnoreResultAssign(); 917 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType(); 918 919 BinOpInfo OpInfo; 920 921 if (E->getComputationResultType()->isAnyComplexType()) { 922 // This needs to go through the complex expression emitter, but it's a tad 923 // complicated to do that... I'm leaving it out for now. (Note that we do 924 // actually need the imaginary part of the RHS for multiplication and 925 // division.) 926 CGF.ErrorUnsupported(E, "complex compound assignment"); 927 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 928 } 929 930 // Emit the RHS first. __block variables need to have the rhs evaluated 931 // first, plus this should improve codegen a little. 932 OpInfo.RHS = Visit(E->getRHS()); 933 OpInfo.Ty = E->getComputationResultType(); 934 OpInfo.E = E; 935 // Load/convert the LHS. 936 LValue LHSLV = EmitLValue(E->getLHS()); 937 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 938 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, 939 E->getComputationLHSType()); 940 941 // Expand the binary operator. 942 Value *Result = (this->*Func)(OpInfo); 943 944 // Convert the result back to the LHS type. 945 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy); 946 947 // Store the result value into the LHS lvalue. Bit-fields are handled 948 // specially because the result is altered by the store, i.e., [C99 6.5.16p1] 949 // 'An assignment expression has the value of the left operand after the 950 // assignment...'. 951 if (LHSLV.isBitfield()) { 952 if (!LHSLV.isVolatileQualified()) { 953 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy, 954 &Result); 955 return Result; 956 } else 957 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy); 958 } else 959 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 960 if (Ignore) 961 return 0; 962 return EmitLoadOfLValue(LHSLV, E->getType()); 963} 964 965 966Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 967 if (Ops.LHS->getType()->isFPOrFPVector()) 968 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 969 else if (Ops.Ty->isUnsignedIntegerType()) 970 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 971 else 972 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 973} 974 975Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 976 // Rem in C can't be a floating point type: C99 6.5.5p2. 977 if (Ops.Ty->isUnsignedIntegerType()) 978 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 979 else 980 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 981} 982 983Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { 984 unsigned IID; 985 unsigned OpID = 0; 986 987 switch (Ops.E->getOpcode()) { 988 case BinaryOperator::Add: 989 case BinaryOperator::AddAssign: 990 OpID = 1; 991 IID = llvm::Intrinsic::sadd_with_overflow; 992 break; 993 case BinaryOperator::Sub: 994 case BinaryOperator::SubAssign: 995 OpID = 2; 996 IID = llvm::Intrinsic::ssub_with_overflow; 997 break; 998 case BinaryOperator::Mul: 999 case BinaryOperator::MulAssign: 1000 OpID = 3; 1001 IID = llvm::Intrinsic::smul_with_overflow; 1002 break; 1003 default: 1004 assert(false && "Unsupported operation for overflow detection"); 1005 IID = 0; 1006 } 1007 OpID <<= 1; 1008 OpID |= 1; 1009 1010 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); 1011 1012 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 1013 1014 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS); 1015 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0); 1016 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1); 1017 1018 // Branch in case of overflow. 1019 llvm::BasicBlock *initialBB = Builder.GetInsertBlock(); 1020 llvm::BasicBlock *overflowBB = 1021 CGF.createBasicBlock("overflow", CGF.CurFn); 1022 llvm::BasicBlock *continueBB = 1023 CGF.createBasicBlock("overflow.continue", CGF.CurFn); 1024 1025 Builder.CreateCondBr(overflow, overflowBB, continueBB); 1026 1027 // Handle overflow 1028 1029 Builder.SetInsertPoint(overflowBB); 1030 1031 // Handler is: 1032 // long long *__overflow_handler)(long long a, long long b, char op, 1033 // char width) 1034 std::vector<const llvm::Type*> handerArgTypes; 1035 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1036 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext)); 1037 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1038 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext)); 1039 llvm::FunctionType *handlerTy = llvm::FunctionType::get( 1040 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false); 1041 llvm::Value *handlerFunction = 1042 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler", 1043 llvm::PointerType::getUnqual(handlerTy)); 1044 handlerFunction = Builder.CreateLoad(handlerFunction); 1045 1046 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction, 1047 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)), 1048 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)), 1049 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID), 1050 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1051 cast<llvm::IntegerType>(opTy)->getBitWidth())); 1052 1053 handlerResult = Builder.CreateTrunc(handlerResult, opTy); 1054 1055 Builder.CreateBr(continueBB); 1056 1057 // Set up the continuation 1058 Builder.SetInsertPoint(continueBB); 1059 // Get the correct result 1060 llvm::PHINode *phi = Builder.CreatePHI(opTy); 1061 phi->reserveOperandSpace(2); 1062 phi->addIncoming(result, initialBB); 1063 phi->addIncoming(handlerResult, overflowBB); 1064 1065 return phi; 1066} 1067 1068Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 1069 if (!Ops.Ty->isAnyPointerType()) { 1070 if (CGF.getContext().getLangOptions().OverflowChecking && 1071 Ops.Ty->isSignedIntegerType()) 1072 return EmitOverflowCheckedBinOp(Ops); 1073 1074 if (Ops.LHS->getType()->isFPOrFPVector()) 1075 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add"); 1076 1077 // Signed integer overflow is undefined behavior. 1078 if (Ops.Ty->isSignedIntegerType()) 1079 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add"); 1080 1081 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 1082 } 1083 1084 if (Ops.Ty->isPointerType() && 1085 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) { 1086 // The amount of the addition needs to account for the VLA size 1087 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition"); 1088 } 1089 Value *Ptr, *Idx; 1090 Expr *IdxExp; 1091 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>(); 1092 const ObjCObjectPointerType *OPT = 1093 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType(); 1094 if (PT || OPT) { 1095 Ptr = Ops.LHS; 1096 Idx = Ops.RHS; 1097 IdxExp = Ops.E->getRHS(); 1098 } else { // int + pointer 1099 PT = Ops.E->getRHS()->getType()->getAs<PointerType>(); 1100 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType(); 1101 assert((PT || OPT) && "Invalid add expr"); 1102 Ptr = Ops.RHS; 1103 Idx = Ops.LHS; 1104 IdxExp = Ops.E->getLHS(); 1105 } 1106 1107 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1108 if (Width < CGF.LLVMPointerWidth) { 1109 // Zero or sign extend the pointer value based on whether the index is 1110 // signed or not. 1111 const llvm::Type *IdxType = 1112 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1113 if (IdxExp->getType()->isSignedIntegerType()) 1114 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1115 else 1116 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1117 } 1118 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType(); 1119 // Handle interface types, which are not represented with a concrete type. 1120 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) { 1121 llvm::Value *InterfaceSize = 1122 llvm::ConstantInt::get(Idx->getType(), 1123 CGF.getContext().getTypeSize(OIT) / 8); 1124 Idx = Builder.CreateMul(Idx, InterfaceSize); 1125 const llvm::Type *i8Ty = 1126 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1127 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1128 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1129 return Builder.CreateBitCast(Res, Ptr->getType()); 1130 } 1131 1132 // Explicitly handle GNU void* and function pointer arithmetic extensions. The 1133 // GNU void* casts amount to no-ops since our void* type is i8*, but this is 1134 // future proof. 1135 if (ElementType->isVoidType() || ElementType->isFunctionType()) { 1136 const llvm::Type *i8Ty = 1137 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1138 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty); 1139 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr"); 1140 return Builder.CreateBitCast(Res, Ptr->getType()); 1141 } 1142 1143 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr"); 1144} 1145 1146Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 1147 if (!isa<llvm::PointerType>(Ops.LHS->getType())) { 1148 if (CGF.getContext().getLangOptions().OverflowChecking 1149 && Ops.Ty->isSignedIntegerType()) 1150 return EmitOverflowCheckedBinOp(Ops); 1151 1152 if (Ops.LHS->getType()->isFPOrFPVector()) 1153 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub"); 1154 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 1155 } 1156 1157 if (Ops.E->getLHS()->getType()->isPointerType() && 1158 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) { 1159 // The amount of the addition needs to account for the VLA size for 1160 // ptr-int 1161 // The amount of the division needs to account for the VLA size for 1162 // ptr-ptr. 1163 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction"); 1164 } 1165 1166 const QualType LHSType = Ops.E->getLHS()->getType(); 1167 const QualType LHSElementType = LHSType->getPointeeType(); 1168 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 1169 // pointer - int 1170 Value *Idx = Ops.RHS; 1171 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 1172 if (Width < CGF.LLVMPointerWidth) { 1173 // Zero or sign extend the pointer value based on whether the index is 1174 // signed or not. 1175 const llvm::Type *IdxType = 1176 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth); 1177 if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 1178 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 1179 else 1180 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 1181 } 1182 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 1183 1184 // Handle interface types, which are not represented with a concrete type. 1185 if (const ObjCInterfaceType *OIT = 1186 dyn_cast<ObjCInterfaceType>(LHSElementType)) { 1187 llvm::Value *InterfaceSize = 1188 llvm::ConstantInt::get(Idx->getType(), 1189 CGF.getContext().getTypeSize(OIT) / 8); 1190 Idx = Builder.CreateMul(Idx, InterfaceSize); 1191 const llvm::Type *i8Ty = 1192 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1193 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1194 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr"); 1195 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1196 } 1197 1198 // Explicitly handle GNU void* and function pointer arithmetic 1199 // extensions. The GNU void* casts amount to no-ops since our void* type is 1200 // i8*, but this is future proof. 1201 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1202 const llvm::Type *i8Ty = 1203 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 1204 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty); 1205 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr"); 1206 return Builder.CreateBitCast(Res, Ops.LHS->getType()); 1207 } 1208 1209 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr"); 1210 } else { 1211 // pointer - pointer 1212 Value *LHS = Ops.LHS; 1213 Value *RHS = Ops.RHS; 1214 1215 uint64_t ElementSize; 1216 1217 // Handle GCC extension for pointer arithmetic on void* and function pointer 1218 // types. 1219 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) { 1220 ElementSize = 1; 1221 } else { 1222 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8; 1223 } 1224 1225 const llvm::Type *ResultType = ConvertType(Ops.Ty); 1226 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 1227 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1228 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 1229 1230 // Optimize out the shift for element size of 1. 1231 if (ElementSize == 1) 1232 return BytesBetween; 1233 1234 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since 1235 // pointer difference in C is only defined in the case where both operands 1236 // are pointing to elements of an array. 1237 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize); 1238 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 1239 } 1240} 1241 1242Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 1243 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1244 // RHS to the same size as the LHS. 1245 Value *RHS = Ops.RHS; 1246 if (Ops.LHS->getType() != RHS->getType()) 1247 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1248 1249 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 1250} 1251 1252Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 1253 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 1254 // RHS to the same size as the LHS. 1255 Value *RHS = Ops.RHS; 1256 if (Ops.LHS->getType() != RHS->getType()) 1257 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 1258 1259 if (Ops.Ty->isUnsignedIntegerType()) 1260 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 1261 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 1262} 1263 1264Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 1265 unsigned SICmpOpc, unsigned FCmpOpc) { 1266 TestAndClearIgnoreResultAssign(); 1267 Value *Result; 1268 QualType LHSTy = E->getLHS()->getType(); 1269 if (!LHSTy->isAnyComplexType()) { 1270 Value *LHS = Visit(E->getLHS()); 1271 Value *RHS = Visit(E->getRHS()); 1272 1273 if (LHS->getType()->isFPOrFPVector()) { 1274 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 1275 LHS, RHS, "cmp"); 1276 } else if (LHSTy->isSignedIntegerType()) { 1277 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 1278 LHS, RHS, "cmp"); 1279 } else { 1280 // Unsigned integers and pointers. 1281 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1282 LHS, RHS, "cmp"); 1283 } 1284 1285 // If this is a vector comparison, sign extend the result to the appropriate 1286 // vector integer type and return it (don't convert to bool). 1287 if (LHSTy->isVectorType()) 1288 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext"); 1289 1290 } else { 1291 // Complex Comparison: can only be an equality comparison. 1292 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 1293 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 1294 1295 QualType CETy = LHSTy->getAsComplexType()->getElementType(); 1296 1297 Value *ResultR, *ResultI; 1298 if (CETy->isRealFloatingType()) { 1299 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1300 LHS.first, RHS.first, "cmp.r"); 1301 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 1302 LHS.second, RHS.second, "cmp.i"); 1303 } else { 1304 // Complex comparisons can only be equality comparisons. As such, signed 1305 // and unsigned opcodes are the same. 1306 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1307 LHS.first, RHS.first, "cmp.r"); 1308 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 1309 LHS.second, RHS.second, "cmp.i"); 1310 } 1311 1312 if (E->getOpcode() == BinaryOperator::EQ) { 1313 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 1314 } else { 1315 assert(E->getOpcode() == BinaryOperator::NE && 1316 "Complex comparison other than == or != ?"); 1317 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 1318 } 1319 } 1320 1321 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType()); 1322} 1323 1324Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1325 bool Ignore = TestAndClearIgnoreResultAssign(); 1326 1327 // __block variables need to have the rhs evaluated first, plus this should 1328 // improve codegen just a little. 1329 Value *RHS = Visit(E->getRHS()); 1330 LValue LHS = EmitLValue(E->getLHS()); 1331 1332 // Store the value into the LHS. Bit-fields are handled specially 1333 // because the result is altered by the store, i.e., [C99 6.5.16p1] 1334 // 'An assignment expression has the value of the left operand after 1335 // the assignment...'. 1336 if (LHS.isBitfield()) { 1337 if (!LHS.isVolatileQualified()) { 1338 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(), 1339 &RHS); 1340 return RHS; 1341 } else 1342 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType()); 1343 } else 1344 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1345 if (Ignore) 1346 return 0; 1347 return EmitLoadOfLValue(LHS, E->getType()); 1348} 1349 1350Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1351 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0. 1352 // If we have 1 && X, just emit X without inserting the control flow. 1353 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1354 if (Cond == 1) { // If we have 1 && X, just emit X. 1355 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1356 // ZExt result to int. 1357 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext"); 1358 } 1359 1360 // 0 && RHS: If it is safe, just elide the RHS, and return 0. 1361 if (!CGF.ContainsLabel(E->getRHS())) 1362 return llvm::Constant::getNullValue(CGF.LLVMIntTy); 1363 } 1364 1365 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end"); 1366 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs"); 1367 1368 // Branch on the LHS first. If it is false, go to the failure (cont) block. 1369 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock); 1370 1371 // Any edges into the ContBlock are now from an (indeterminate number of) 1372 // edges from this first condition. All of these values will be false. Start 1373 // setting up the PHI node in the Cont Block for this. 1374 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1375 "", ContBlock); 1376 PN->reserveOperandSpace(2); // Normal case, two inputs. 1377 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1378 PI != PE; ++PI) 1379 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI); 1380 1381 CGF.PushConditionalTempDestruction(); 1382 CGF.EmitBlock(RHSBlock); 1383 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1384 CGF.PopConditionalTempDestruction(); 1385 1386 // Reaquire the RHS block, as there may be subblocks inserted. 1387 RHSBlock = Builder.GetInsertBlock(); 1388 1389 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1390 // into the phi node for the edge with the value of RHSCond. 1391 CGF.EmitBlock(ContBlock); 1392 PN->addIncoming(RHSCond, RHSBlock); 1393 1394 // ZExt result to int. 1395 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext"); 1396} 1397 1398Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1399 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1. 1400 // If we have 0 || X, just emit X without inserting the control flow. 1401 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) { 1402 if (Cond == -1) { // If we have 0 || X, just emit X. 1403 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1404 // ZExt result to int. 1405 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext"); 1406 } 1407 1408 // 1 || RHS: If it is safe, just elide the RHS, and return 1. 1409 if (!CGF.ContainsLabel(E->getRHS())) 1410 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1); 1411 } 1412 1413 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end"); 1414 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs"); 1415 1416 // Branch on the LHS first. If it is true, go to the success (cont) block. 1417 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock); 1418 1419 // Any edges into the ContBlock are now from an (indeterminate number of) 1420 // edges from this first condition. All of these values will be true. Start 1421 // setting up the PHI node in the Cont Block for this. 1422 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 1423 "", ContBlock); 1424 PN->reserveOperandSpace(2); // Normal case, two inputs. 1425 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock); 1426 PI != PE; ++PI) 1427 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI); 1428 1429 CGF.PushConditionalTempDestruction(); 1430 1431 // Emit the RHS condition as a bool value. 1432 CGF.EmitBlock(RHSBlock); 1433 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1434 1435 CGF.PopConditionalTempDestruction(); 1436 1437 // Reaquire the RHS block, as there may be subblocks inserted. 1438 RHSBlock = Builder.GetInsertBlock(); 1439 1440 // Emit an unconditional branch from this block to ContBlock. Insert an entry 1441 // into the phi node for the edge with the value of RHSCond. 1442 CGF.EmitBlock(ContBlock); 1443 PN->addIncoming(RHSCond, RHSBlock); 1444 1445 // ZExt result to int. 1446 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext"); 1447} 1448 1449Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1450 CGF.EmitStmt(E->getLHS()); 1451 CGF.EnsureInsertPoint(); 1452 return Visit(E->getRHS()); 1453} 1454 1455//===----------------------------------------------------------------------===// 1456// Other Operators 1457//===----------------------------------------------------------------------===// 1458 1459/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified 1460/// expression is cheap enough and side-effect-free enough to evaluate 1461/// unconditionally instead of conditionally. This is used to convert control 1462/// flow into selects in some cases. 1463static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) { 1464 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 1465 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr()); 1466 1467 // TODO: Allow anything we can constant fold to an integer or fp constant. 1468 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) || 1469 isa<FloatingLiteral>(E)) 1470 return true; 1471 1472 // Non-volatile automatic variables too, to get "cond ? X : Y" where 1473 // X and Y are local variables. 1474 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1475 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1476 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified()) 1477 return true; 1478 1479 return false; 1480} 1481 1482 1483Value *ScalarExprEmitter:: 1484VisitConditionalOperator(const ConditionalOperator *E) { 1485 TestAndClearIgnoreResultAssign(); 1486 // If the condition constant folds and can be elided, try to avoid emitting 1487 // the condition and the dead arm. 1488 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1489 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1490 if (Cond == -1) 1491 std::swap(Live, Dead); 1492 1493 // If the dead side doesn't have labels we need, and if the Live side isn't 1494 // the gnu missing ?: extension (which we could handle, but don't bother 1495 // to), just emit the Live part. 1496 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1497 Live) // Live part isn't missing. 1498 return Visit(Live); 1499 } 1500 1501 1502 // If this is a really simple expression (like x ? 4 : 5), emit this as a 1503 // select instead of as control flow. We can only do this if it is cheap and 1504 // safe to evaluate the LHS and RHS unconditionally. 1505 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) && 1506 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) { 1507 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond()); 1508 llvm::Value *LHS = Visit(E->getLHS()); 1509 llvm::Value *RHS = Visit(E->getRHS()); 1510 return Builder.CreateSelect(CondV, LHS, RHS, "cond"); 1511 } 1512 1513 1514 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1515 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1516 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1517 Value *CondVal = 0; 1518 1519 // If we don't have the GNU missing condition extension, emit a branch on bool 1520 // the normal way. 1521 if (E->getLHS()) { 1522 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for 1523 // the branch on bool. 1524 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1525 } else { 1526 // Otherwise, for the ?: extension, evaluate the conditional and then 1527 // convert it to bool the hard way. We do this explicitly because we need 1528 // the unconverted value for the missing middle value of the ?:. 1529 CondVal = CGF.EmitScalarExpr(E->getCond()); 1530 1531 // In some cases, EmitScalarConversion will delete the "CondVal" expression 1532 // if there are no extra uses (an optimization). Inhibit this by making an 1533 // extra dead use, because we're going to add a use of CondVal later. We 1534 // don't use the builder for this, because we don't want it to get optimized 1535 // away. This leaves dead code, but the ?: extension isn't common. 1536 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder", 1537 Builder.GetInsertBlock()); 1538 1539 Value *CondBoolVal = 1540 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1541 CGF.getContext().BoolTy); 1542 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1543 } 1544 1545 CGF.PushConditionalTempDestruction(); 1546 CGF.EmitBlock(LHSBlock); 1547 1548 // Handle the GNU extension for missing LHS. 1549 Value *LHS; 1550 if (E->getLHS()) 1551 LHS = Visit(E->getLHS()); 1552 else // Perform promotions, to handle cases like "short ?: int" 1553 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1554 1555 CGF.PopConditionalTempDestruction(); 1556 LHSBlock = Builder.GetInsertBlock(); 1557 CGF.EmitBranch(ContBlock); 1558 1559 CGF.PushConditionalTempDestruction(); 1560 CGF.EmitBlock(RHSBlock); 1561 1562 Value *RHS = Visit(E->getRHS()); 1563 CGF.PopConditionalTempDestruction(); 1564 RHSBlock = Builder.GetInsertBlock(); 1565 CGF.EmitBranch(ContBlock); 1566 1567 CGF.EmitBlock(ContBlock); 1568 1569 if (!LHS || !RHS) { 1570 assert(E->getType()->isVoidType() && "Non-void value should have a value"); 1571 return 0; 1572 } 1573 1574 // Create a PHI node for the real part. 1575 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1576 PN->reserveOperandSpace(2); 1577 PN->addIncoming(LHS, LHSBlock); 1578 PN->addIncoming(RHS, RHSBlock); 1579 return PN; 1580} 1581 1582Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1583 return Visit(E->getChosenSubExpr(CGF.getContext())); 1584} 1585 1586Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1587 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 1588 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1589 1590 // If EmitVAArg fails, we fall back to the LLVM instruction. 1591 if (!ArgPtr) 1592 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1593 1594 // FIXME Volatility. 1595 return Builder.CreateLoad(ArgPtr); 1596} 1597 1598Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) { 1599 return CGF.BuildBlockLiteralTmp(BE); 1600} 1601 1602//===----------------------------------------------------------------------===// 1603// Entry Point into this File 1604//===----------------------------------------------------------------------===// 1605 1606/// EmitScalarExpr - Emit the computation of the specified expression of scalar 1607/// type, ignoring the result. 1608Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) { 1609 assert(E && !hasAggregateLLVMType(E->getType()) && 1610 "Invalid scalar expression to emit"); 1611 1612 return ScalarExprEmitter(*this, IgnoreResultAssign) 1613 .Visit(const_cast<Expr*>(E)); 1614} 1615 1616/// EmitScalarConversion - Emit a conversion from the specified type to the 1617/// specified destination type, both of which are LLVM scalar types. 1618Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1619 QualType DstTy) { 1620 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1621 "Invalid scalar expression to emit"); 1622 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1623} 1624 1625/// EmitComplexToScalarConversion - Emit a conversion from the specified complex 1626/// type to the specified destination type, where the destination type is an 1627/// LLVM scalar type. 1628Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1629 QualType SrcTy, 1630 QualType DstTy) { 1631 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1632 "Invalid complex -> scalar conversion"); 1633 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1634 DstTy); 1635} 1636 1637Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) { 1638 assert(V1->getType() == V2->getType() && 1639 "Vector operands must be of the same type"); 1640 unsigned NumElements = 1641 cast<llvm::VectorType>(V1->getType())->getNumElements(); 1642 1643 va_list va; 1644 va_start(va, V2); 1645 1646 llvm::SmallVector<llvm::Constant*, 16> Args; 1647 for (unsigned i = 0; i < NumElements; i++) { 1648 int n = va_arg(va, int); 1649 assert(n >= 0 && n < (int)NumElements * 2 && 1650 "Vector shuffle index out of bounds!"); 1651 Args.push_back(llvm::ConstantInt::get( 1652 llvm::Type::getInt32Ty(VMContext), n)); 1653 } 1654 1655 const char *Name = va_arg(va, const char *); 1656 va_end(va); 1657 1658 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 1659 1660 return Builder.CreateShuffleVector(V1, V2, Mask, Name); 1661} 1662 1663llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals, 1664 unsigned NumVals, bool isSplat) { 1665 llvm::Value *Vec 1666 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals)); 1667 1668 for (unsigned i = 0, e = NumVals; i != e; ++i) { 1669 llvm::Value *Val = isSplat ? Vals[0] : Vals[i]; 1670 llvm::Value *Idx = llvm::ConstantInt::get( 1671 llvm::Type::getInt32Ty(VMContext), i); 1672 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp"); 1673 } 1674 1675 return Vec; 1676} 1677