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