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