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