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