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