clang API Documentation

CGExprComplex.cpp
Go to the documentation of this file.
00001 //===--- CGExprComplex.cpp - Emit LLVM Code for Complex Exprs -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Expr nodes with complex types as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CodeGenModule.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/StmtVisitor.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/Function.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/MDBuilder.h"
00024 #include "llvm/IR/Metadata.h"
00025 #include <algorithm>
00026 using namespace clang;
00027 using namespace CodeGen;
00028 
00029 //===----------------------------------------------------------------------===//
00030 //                        Complex Expression Emitter
00031 //===----------------------------------------------------------------------===//
00032 
00033 typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
00034 
00035 /// Return the complex type that we are meant to emit.
00036 static const ComplexType *getComplexType(QualType type) {
00037   type = type.getCanonicalType();
00038   if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
00039     return comp;
00040   } else {
00041     return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
00042   }
00043 }
00044 
00045 namespace  {
00046 class ComplexExprEmitter
00047   : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
00048   CodeGenFunction &CGF;
00049   CGBuilderTy &Builder;
00050   bool IgnoreReal;
00051   bool IgnoreImag;
00052 public:
00053   ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
00054     : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
00055   }
00056 
00057 
00058   //===--------------------------------------------------------------------===//
00059   //                               Utilities
00060   //===--------------------------------------------------------------------===//
00061 
00062   bool TestAndClearIgnoreReal() {
00063     bool I = IgnoreReal;
00064     IgnoreReal = false;
00065     return I;
00066   }
00067   bool TestAndClearIgnoreImag() {
00068     bool I = IgnoreImag;
00069     IgnoreImag = false;
00070     return I;
00071   }
00072 
00073   /// EmitLoadOfLValue - Given an expression with complex type that represents a
00074   /// value l-value, this method emits the address of the l-value, then loads
00075   /// and returns the result.
00076   ComplexPairTy EmitLoadOfLValue(const Expr *E) {
00077     return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
00078   }
00079 
00080   ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
00081 
00082   /// EmitStoreOfComplex - Store the specified real/imag parts into the
00083   /// specified value pointer.
00084   void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
00085 
00086   /// EmitComplexToComplexCast - Emit a cast from complex value Val to DestType.
00087   ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
00088                                          QualType DestType);
00089   /// EmitComplexToComplexCast - Emit a cast from scalar value Val to DestType.
00090   ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
00091                                         QualType DestType);
00092 
00093   //===--------------------------------------------------------------------===//
00094   //                            Visitor Methods
00095   //===--------------------------------------------------------------------===//
00096 
00097   ComplexPairTy Visit(Expr *E) {
00098     return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
00099   }
00100 
00101   ComplexPairTy VisitStmt(Stmt *S) {
00102     S->dump(CGF.getContext().getSourceManager());
00103     llvm_unreachable("Stmt can't have complex result type!");
00104   }
00105   ComplexPairTy VisitExpr(Expr *S);
00106   ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
00107   ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
00108     return Visit(GE->getResultExpr());
00109   }
00110   ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
00111   ComplexPairTy
00112   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
00113     return Visit(PE->getReplacement());
00114   }
00115 
00116   // l-values.
00117   ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
00118     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
00119       if (result.isReference())
00120         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
00121                                 E->getExprLoc());
00122 
00123       llvm::Constant *pair = result.getValue();
00124       return ComplexPairTy(pair->getAggregateElement(0U),
00125                            pair->getAggregateElement(1U));
00126     }
00127     return EmitLoadOfLValue(E);
00128   }
00129   ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
00130     return EmitLoadOfLValue(E);
00131   }
00132   ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
00133     return CGF.EmitObjCMessageExpr(E).getComplexVal();
00134   }
00135   ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
00136   ComplexPairTy VisitMemberExpr(const Expr *E) { return EmitLoadOfLValue(E); }
00137   ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
00138     if (E->isGLValue())
00139       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
00140     return CGF.getOpaqueRValueMapping(E).getComplexVal();
00141   }
00142 
00143   ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
00144     return CGF.EmitPseudoObjectRValue(E).getComplexVal();
00145   }
00146 
00147   // FIXME: CompoundLiteralExpr
00148 
00149   ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
00150   ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
00151     // Unlike for scalars, we don't have to worry about function->ptr demotion
00152     // here.
00153     return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
00154   }
00155   ComplexPairTy VisitCastExpr(CastExpr *E) {
00156     return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
00157   }
00158   ComplexPairTy VisitCallExpr(const CallExpr *E);
00159   ComplexPairTy VisitStmtExpr(const StmtExpr *E);
00160 
00161   // Operators.
00162   ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
00163                                    bool isInc, bool isPre) {
00164     LValue LV = CGF.EmitLValue(E->getSubExpr());
00165     return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
00166   }
00167   ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
00168     return VisitPrePostIncDec(E, false, false);
00169   }
00170   ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
00171     return VisitPrePostIncDec(E, true, false);
00172   }
00173   ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
00174     return VisitPrePostIncDec(E, false, true);
00175   }
00176   ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
00177     return VisitPrePostIncDec(E, true, true);
00178   }
00179   ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
00180   ComplexPairTy VisitUnaryPlus     (const UnaryOperator *E) {
00181     TestAndClearIgnoreReal();
00182     TestAndClearIgnoreImag();
00183     return Visit(E->getSubExpr());
00184   }
00185   ComplexPairTy VisitUnaryMinus    (const UnaryOperator *E);
00186   ComplexPairTy VisitUnaryNot      (const UnaryOperator *E);
00187   // LNot,Real,Imag never return complex.
00188   ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
00189     return Visit(E->getSubExpr());
00190   }
00191   ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
00192     return Visit(DAE->getExpr());
00193   }
00194   ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
00195     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
00196     return Visit(DIE->getExpr());
00197   }
00198   ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
00199     CGF.enterFullExpression(E);
00200     CodeGenFunction::RunCleanupsScope Scope(CGF);
00201     return Visit(E->getSubExpr());
00202   }
00203   ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
00204     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
00205     QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
00206     llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
00207     return ComplexPairTy(Null, Null);
00208   }
00209   ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
00210     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
00211     QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
00212     llvm::Constant *Null =
00213                        llvm::Constant::getNullValue(CGF.ConvertType(Elem));
00214     return ComplexPairTy(Null, Null);
00215   }
00216 
00217   struct BinOpInfo {
00218     ComplexPairTy LHS;
00219     ComplexPairTy RHS;
00220     QualType Ty;  // Computation Type.
00221   };
00222 
00223   BinOpInfo EmitBinOps(const BinaryOperator *E);
00224   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
00225                                   ComplexPairTy (ComplexExprEmitter::*Func)
00226                                   (const BinOpInfo &),
00227                                   RValue &Val);
00228   ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,
00229                                    ComplexPairTy (ComplexExprEmitter::*Func)
00230                                    (const BinOpInfo &));
00231 
00232   ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
00233   ComplexPairTy EmitBinSub(const BinOpInfo &Op);
00234   ComplexPairTy EmitBinMul(const BinOpInfo &Op);
00235   ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
00236 
00237   ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
00238                                         const BinOpInfo &Op);
00239 
00240   ComplexPairTy VisitBinAdd(const BinaryOperator *E) {
00241     return EmitBinAdd(EmitBinOps(E));
00242   }
00243   ComplexPairTy VisitBinSub(const BinaryOperator *E) {
00244     return EmitBinSub(EmitBinOps(E));
00245   }
00246   ComplexPairTy VisitBinMul(const BinaryOperator *E) {
00247     return EmitBinMul(EmitBinOps(E));
00248   }
00249   ComplexPairTy VisitBinDiv(const BinaryOperator *E) {
00250     return EmitBinDiv(EmitBinOps(E));
00251   }
00252 
00253   // Compound assignments.
00254   ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
00255     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
00256   }
00257   ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
00258     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
00259   }
00260   ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
00261     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
00262   }
00263   ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
00264     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
00265   }
00266 
00267   // GCC rejects rem/and/or/xor for integer complex.
00268   // Logical and/or always return int, never complex.
00269 
00270   // No comparisons produce a complex result.
00271 
00272   LValue EmitBinAssignLValue(const BinaryOperator *E,
00273                              ComplexPairTy &Val);
00274   ComplexPairTy VisitBinAssign     (const BinaryOperator *E);
00275   ComplexPairTy VisitBinComma      (const BinaryOperator *E);
00276 
00277 
00278   ComplexPairTy
00279   VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
00280   ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
00281 
00282   ComplexPairTy VisitInitListExpr(InitListExpr *E);
00283 
00284   ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
00285     return EmitLoadOfLValue(E);
00286   }
00287 
00288   ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
00289 
00290   ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
00291     return CGF.EmitAtomicExpr(E).getComplexVal();
00292   }
00293 };
00294 }  // end anonymous namespace.
00295 
00296 //===----------------------------------------------------------------------===//
00297 //                                Utilities
00298 //===----------------------------------------------------------------------===//
00299 
00300 /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
00301 /// load the real and imaginary pieces, returning them as Real/Imag.
00302 ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
00303                                                    SourceLocation loc) {
00304   assert(lvalue.isSimple() && "non-simple complex l-value?");
00305   if (lvalue.getType()->isAtomicType())
00306     return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
00307 
00308   llvm::Value *SrcPtr = lvalue.getAddress();
00309   bool isVolatile = lvalue.isVolatileQualified();
00310   unsigned AlignR = lvalue.getAlignment().getQuantity();
00311   ASTContext &C = CGF.getContext();
00312   QualType ComplexTy = lvalue.getType();
00313   unsigned ComplexAlign = C.getTypeAlignInChars(ComplexTy).getQuantity();
00314   unsigned AlignI = std::min(AlignR, ComplexAlign);
00315 
00316   llvm::Value *Real=nullptr, *Imag=nullptr;
00317 
00318   if (!IgnoreReal || isVolatile) {
00319     llvm::Value *RealP = Builder.CreateStructGEP(SrcPtr, 0,
00320                                                  SrcPtr->getName() + ".realp");
00321     Real = Builder.CreateAlignedLoad(RealP, AlignR, isVolatile,
00322                                      SrcPtr->getName() + ".real");
00323   }
00324 
00325   if (!IgnoreImag || isVolatile) {
00326     llvm::Value *ImagP = Builder.CreateStructGEP(SrcPtr, 1,
00327                                                  SrcPtr->getName() + ".imagp");
00328     Imag = Builder.CreateAlignedLoad(ImagP, AlignI, isVolatile,
00329                                      SrcPtr->getName() + ".imag");
00330   }
00331   return ComplexPairTy(Real, Imag);
00332 }
00333 
00334 /// EmitStoreOfComplex - Store the specified real/imag parts into the
00335 /// specified value pointer.
00336 void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val,
00337                                             LValue lvalue,
00338                                             bool isInit) {
00339   if (lvalue.getType()->isAtomicType())
00340     return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
00341 
00342   llvm::Value *Ptr = lvalue.getAddress();
00343   llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, "real");
00344   llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, "imag");
00345   unsigned AlignR = lvalue.getAlignment().getQuantity();
00346   ASTContext &C = CGF.getContext();
00347   QualType ComplexTy = lvalue.getType();
00348   unsigned ComplexAlign = C.getTypeAlignInChars(ComplexTy).getQuantity();
00349   unsigned AlignI = std::min(AlignR, ComplexAlign);
00350 
00351   Builder.CreateAlignedStore(Val.first, RealPtr, AlignR,
00352                              lvalue.isVolatileQualified());
00353   Builder.CreateAlignedStore(Val.second, ImagPtr, AlignI,
00354                              lvalue.isVolatileQualified());
00355 }
00356 
00357 
00358 
00359 //===----------------------------------------------------------------------===//
00360 //                            Visitor Methods
00361 //===----------------------------------------------------------------------===//
00362 
00363 ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
00364   CGF.ErrorUnsupported(E, "complex expression");
00365   llvm::Type *EltTy =
00366     CGF.ConvertType(getComplexType(E->getType())->getElementType());
00367   llvm::Value *U = llvm::UndefValue::get(EltTy);
00368   return ComplexPairTy(U, U);
00369 }
00370 
00371 ComplexPairTy ComplexExprEmitter::
00372 VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
00373   llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
00374   return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
00375 }
00376 
00377 
00378 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
00379   if (E->getCallReturnType()->isReferenceType())
00380     return EmitLoadOfLValue(E);
00381 
00382   return CGF.EmitCallExpr(E).getComplexVal();
00383 }
00384 
00385 ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
00386   CodeGenFunction::StmtExprEvaluation eval(CGF);
00387   llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
00388   assert(RetAlloca && "Expected complex return value");
00389   return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
00390                           E->getExprLoc());
00391 }
00392 
00393 /// EmitComplexToComplexCast - Emit a cast from complex value Val to DestType.
00394 ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
00395                                                            QualType SrcType,
00396                                                            QualType DestType) {
00397   // Get the src/dest element type.
00398   SrcType = SrcType->castAs<ComplexType>()->getElementType();
00399   DestType = DestType->castAs<ComplexType>()->getElementType();
00400 
00401   // C99 6.3.1.6: When a value of complex type is converted to another
00402   // complex type, both the real and imaginary parts follow the conversion
00403   // rules for the corresponding real types.
00404   Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType);
00405   Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType);
00406   return Val;
00407 }
00408 
00409 ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
00410                                                           QualType SrcType,
00411                                                           QualType DestType) {
00412   // Convert the input element to the element type of the complex.
00413   DestType = DestType->castAs<ComplexType>()->getElementType();
00414   Val = CGF.EmitScalarConversion(Val, SrcType, DestType);
00415 
00416   // Return (realval, 0).
00417   return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
00418 }
00419 
00420 ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
00421                                            QualType DestTy) {
00422   switch (CK) {
00423   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
00424 
00425   // Atomic to non-atomic casts may be more than a no-op for some platforms and
00426   // for some types.
00427   case CK_AtomicToNonAtomic:
00428   case CK_NonAtomicToAtomic:
00429   case CK_NoOp:
00430   case CK_LValueToRValue:
00431   case CK_UserDefinedConversion:
00432     return Visit(Op);
00433 
00434   case CK_LValueBitCast: {
00435     LValue origLV = CGF.EmitLValue(Op);
00436     llvm::Value *V = origLV.getAddress();
00437     V = Builder.CreateBitCast(V,
00438                     CGF.ConvertType(CGF.getContext().getPointerType(DestTy)));
00439     return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy,
00440                                                origLV.getAlignment()),
00441                             Op->getExprLoc());
00442   }
00443 
00444   case CK_BitCast:
00445   case CK_BaseToDerived:
00446   case CK_DerivedToBase:
00447   case CK_UncheckedDerivedToBase:
00448   case CK_Dynamic:
00449   case CK_ToUnion:
00450   case CK_ArrayToPointerDecay:
00451   case CK_FunctionToPointerDecay:
00452   case CK_NullToPointer:
00453   case CK_NullToMemberPointer:
00454   case CK_BaseToDerivedMemberPointer:
00455   case CK_DerivedToBaseMemberPointer:
00456   case CK_MemberPointerToBoolean:
00457   case CK_ReinterpretMemberPointer:
00458   case CK_ConstructorConversion:
00459   case CK_IntegralToPointer:
00460   case CK_PointerToIntegral:
00461   case CK_PointerToBoolean:
00462   case CK_ToVoid:
00463   case CK_VectorSplat:
00464   case CK_IntegralCast:
00465   case CK_IntegralToBoolean:
00466   case CK_IntegralToFloating:
00467   case CK_FloatingToIntegral:
00468   case CK_FloatingToBoolean:
00469   case CK_FloatingCast:
00470   case CK_CPointerToObjCPointerCast:
00471   case CK_BlockPointerToObjCPointerCast:
00472   case CK_AnyPointerToBlockPointerCast:
00473   case CK_ObjCObjectLValueCast:
00474   case CK_FloatingComplexToReal:
00475   case CK_FloatingComplexToBoolean:
00476   case CK_IntegralComplexToReal:
00477   case CK_IntegralComplexToBoolean:
00478   case CK_ARCProduceObject:
00479   case CK_ARCConsumeObject:
00480   case CK_ARCReclaimReturnedObject:
00481   case CK_ARCExtendBlockObject:
00482   case CK_CopyAndAutoreleaseBlockObject:
00483   case CK_BuiltinFnToFnPtr:
00484   case CK_ZeroToOCLEvent:
00485   case CK_AddressSpaceConversion:
00486     llvm_unreachable("invalid cast kind for complex value");
00487 
00488   case CK_FloatingRealToComplex:
00489   case CK_IntegralRealToComplex:
00490     return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op),
00491                                    Op->getType(), DestTy);
00492 
00493   case CK_FloatingComplexCast:
00494   case CK_FloatingComplexToIntegralComplex:
00495   case CK_IntegralComplexCast:
00496   case CK_IntegralComplexToFloatingComplex:
00497     return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy);
00498   }
00499 
00500   llvm_unreachable("unknown cast resulting in complex value");
00501 }
00502 
00503 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
00504   TestAndClearIgnoreReal();
00505   TestAndClearIgnoreImag();
00506   ComplexPairTy Op = Visit(E->getSubExpr());
00507 
00508   llvm::Value *ResR, *ResI;
00509   if (Op.first->getType()->isFloatingPointTy()) {
00510     ResR = Builder.CreateFNeg(Op.first,  "neg.r");
00511     ResI = Builder.CreateFNeg(Op.second, "neg.i");
00512   } else {
00513     ResR = Builder.CreateNeg(Op.first,  "neg.r");
00514     ResI = Builder.CreateNeg(Op.second, "neg.i");
00515   }
00516   return ComplexPairTy(ResR, ResI);
00517 }
00518 
00519 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
00520   TestAndClearIgnoreReal();
00521   TestAndClearIgnoreImag();
00522   // ~(a+ib) = a + i*-b
00523   ComplexPairTy Op = Visit(E->getSubExpr());
00524   llvm::Value *ResI;
00525   if (Op.second->getType()->isFloatingPointTy())
00526     ResI = Builder.CreateFNeg(Op.second, "conj.i");
00527   else
00528     ResI = Builder.CreateNeg(Op.second, "conj.i");
00529 
00530   return ComplexPairTy(Op.first, ResI);
00531 }
00532 
00533 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
00534   llvm::Value *ResR, *ResI;
00535 
00536   if (Op.LHS.first->getType()->isFloatingPointTy()) {
00537     ResR = Builder.CreateFAdd(Op.LHS.first,  Op.RHS.first,  "add.r");
00538     if (Op.LHS.second && Op.RHS.second)
00539       ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
00540     else
00541       ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
00542     assert(ResI && "Only one operand may be real!");
00543   } else {
00544     ResR = Builder.CreateAdd(Op.LHS.first,  Op.RHS.first,  "add.r");
00545     assert(Op.LHS.second && Op.RHS.second &&
00546            "Both operands of integer complex operators must be complex!");
00547     ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
00548   }
00549   return ComplexPairTy(ResR, ResI);
00550 }
00551 
00552 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
00553   llvm::Value *ResR, *ResI;
00554   if (Op.LHS.first->getType()->isFloatingPointTy()) {
00555     ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
00556     if (Op.LHS.second && Op.RHS.second)
00557       ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
00558     else
00559       ResI = Op.LHS.second ? Op.LHS.second
00560                            : Builder.CreateFNeg(Op.RHS.second, "sub.i");
00561     assert(ResI && "Only one operand may be real!");
00562   } else {
00563     ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
00564     assert(Op.LHS.second && Op.RHS.second &&
00565            "Both operands of integer complex operators must be complex!");
00566     ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
00567   }
00568   return ComplexPairTy(ResR, ResI);
00569 }
00570 
00571 /// \brief Emit a libcall for a binary operation on complex types.
00572 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
00573                                                           const BinOpInfo &Op) {
00574   CallArgList Args;
00575   Args.add(RValue::get(Op.LHS.first),
00576            Op.Ty->castAs<ComplexType>()->getElementType());
00577   Args.add(RValue::get(Op.LHS.second),
00578            Op.Ty->castAs<ComplexType>()->getElementType());
00579   Args.add(RValue::get(Op.RHS.first),
00580            Op.Ty->castAs<ComplexType>()->getElementType());
00581   Args.add(RValue::get(Op.RHS.second),
00582            Op.Ty->castAs<ComplexType>()->getElementType());
00583 
00584   // We *must* use the full CG function call building logic here because the
00585   // complex type has special ABI handling.
00586   const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
00587       Op.Ty, Args, FunctionType::ExtInfo(), RequiredArgs::All);
00588   llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
00589   llvm::Constant *Func = CGF.CGM.CreateRuntimeFunction(FTy, LibCallName);
00590 
00591   return CGF.EmitCall(FuncInfo, Func, ReturnValueSlot(), Args).getComplexVal();
00592 }
00593 
00594 /// \brief Lookup the libcall name for a given floating point type complex
00595 /// multiply.
00596 static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
00597   switch (Ty->getTypeID()) {
00598   default:
00599     llvm_unreachable("Unsupported floating point type!");
00600   case llvm::Type::HalfTyID:
00601     return "__mulhc3";
00602   case llvm::Type::FloatTyID:
00603     return "__mulsc3";
00604   case llvm::Type::DoubleTyID:
00605     return "__muldc3";
00606   case llvm::Type::PPC_FP128TyID:
00607     return "__multc3";
00608   case llvm::Type::X86_FP80TyID:
00609     return "__mulxc3";
00610   case llvm::Type::FP128TyID:
00611     return "__multc3";
00612   }
00613 }
00614 
00615 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
00616 // typed values.
00617 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
00618   using llvm::Value;
00619   Value *ResR, *ResI;
00620   llvm::MDBuilder MDHelper(CGF.getLLVMContext());
00621 
00622   if (Op.LHS.first->getType()->isFloatingPointTy()) {
00623     // The general formulation is:
00624     // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
00625     //
00626     // But we can fold away components which would be zero due to a real
00627     // operand according to C11 Annex G.5.1p2.
00628     // FIXME: C11 also provides for imaginary types which would allow folding
00629     // still more of this within the type system.
00630 
00631     if (Op.LHS.second && Op.RHS.second) {
00632       // If both operands are complex, emit the core math directly, and then
00633       // test for NaNs. If we find NaNs in the result, we delegate to a libcall
00634       // to carefully re-compute the correct infinity representation if
00635       // possible. The expectation is that the presence of NaNs here is
00636       // *extremely* rare, and so the cost of the libcall is almost irrelevant.
00637       // This is good, because the libcall re-computes the core multiplication
00638       // exactly the same as we do here and re-tests for NaNs in order to be
00639       // a generic complex*complex libcall.
00640 
00641       // First compute the four products.
00642       Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
00643       Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
00644       Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
00645       Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
00646 
00647       // The real part is the difference of the first two, the imaginary part is
00648       // the sum of the second.
00649       ResR = Builder.CreateFSub(AC, BD, "mul_r");
00650       ResI = Builder.CreateFAdd(AD, BC, "mul_i");
00651 
00652       // Emit the test for the real part becoming NaN and create a branch to
00653       // handle it. We test for NaN by comparing the number to itself.
00654       Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
00655       llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
00656       llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
00657       llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
00658       llvm::BasicBlock *OrigBB = Branch->getParent();
00659 
00660       // Give hint that we very much don't expect to see NaNs.
00661       // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
00662       llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
00663       Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
00664 
00665       // Now test the imaginary part and create its branch.
00666       CGF.EmitBlock(INaNBB);
00667       Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
00668       llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
00669       Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
00670       Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
00671 
00672       // Now emit the libcall on this slowest of the slow paths.
00673       CGF.EmitBlock(LibCallBB);
00674       Value *LibCallR, *LibCallI;
00675       std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
00676           getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
00677       Builder.CreateBr(ContBB);
00678 
00679       // Finally continue execution by phi-ing together the different
00680       // computation paths.
00681       CGF.EmitBlock(ContBB);
00682       llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
00683       RealPHI->addIncoming(ResR, OrigBB);
00684       RealPHI->addIncoming(ResR, INaNBB);
00685       RealPHI->addIncoming(LibCallR, LibCallBB);
00686       llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
00687       ImagPHI->addIncoming(ResI, OrigBB);
00688       ImagPHI->addIncoming(ResI, INaNBB);
00689       ImagPHI->addIncoming(LibCallI, LibCallBB);
00690       return ComplexPairTy(RealPHI, ImagPHI);
00691     }
00692     assert((Op.LHS.second || Op.RHS.second) &&
00693            "At least one operand must be complex!");
00694 
00695     // If either of the operands is a real rather than a complex, the
00696     // imaginary component is ignored when computing the real component of the
00697     // result.
00698     ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
00699 
00700     ResI = Op.LHS.second
00701                ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
00702                : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
00703   } else {
00704     assert(Op.LHS.second && Op.RHS.second &&
00705            "Both operands of integer complex operators must be complex!");
00706     Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
00707     Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
00708     ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
00709 
00710     Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
00711     Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
00712     ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
00713   }
00714   return ComplexPairTy(ResR, ResI);
00715 }
00716 
00717 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
00718 // typed values.
00719 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
00720   llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
00721   llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
00722 
00723 
00724   llvm::Value *DSTr, *DSTi;
00725   if (LHSr->getType()->isFloatingPointTy()) {
00726     // If we have a complex operand on the RHS, we delegate to a libcall to
00727     // handle all of the complexities and minimize underflow/overflow cases.
00728     //
00729     // FIXME: We would be able to avoid the libcall in many places if we
00730     // supported imaginary types in addition to complex types.
00731     if (RHSi) {
00732       BinOpInfo LibCallOp = Op;
00733       // If LHS was a real, supply a null imaginary part.
00734       if (!LHSi)
00735         LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
00736 
00737       StringRef LibCallName;
00738       switch (LHSr->getType()->getTypeID()) {
00739       default:
00740         llvm_unreachable("Unsupported floating point type!");
00741       case llvm::Type::HalfTyID:
00742         return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
00743       case llvm::Type::FloatTyID:
00744         return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
00745       case llvm::Type::DoubleTyID:
00746         return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
00747       case llvm::Type::PPC_FP128TyID:
00748         return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
00749       case llvm::Type::X86_FP80TyID:
00750         return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
00751       case llvm::Type::FP128TyID:
00752         return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
00753       }
00754     }
00755     assert(LHSi && "Can have at most one non-complex operand!");
00756 
00757     DSTr = Builder.CreateFDiv(LHSr, RHSr);
00758     DSTi = Builder.CreateFDiv(LHSi, RHSr);
00759   } else {
00760     assert(Op.LHS.second && Op.RHS.second &&
00761            "Both operands of integer complex operators must be complex!");
00762     // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
00763     llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
00764     llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
00765     llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
00766 
00767     llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
00768     llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
00769     llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
00770 
00771     llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
00772     llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
00773     llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
00774 
00775     if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
00776       DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
00777       DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
00778     } else {
00779       DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
00780       DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
00781     }
00782   }
00783 
00784   return ComplexPairTy(DSTr, DSTi);
00785 }
00786 
00787 ComplexExprEmitter::BinOpInfo
00788 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
00789   TestAndClearIgnoreReal();
00790   TestAndClearIgnoreImag();
00791   BinOpInfo Ops;
00792   if (E->getLHS()->getType()->isRealFloatingType())
00793     Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
00794   else
00795     Ops.LHS = Visit(E->getLHS());
00796   if (E->getRHS()->getType()->isRealFloatingType())
00797     Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
00798   else
00799     Ops.RHS = Visit(E->getRHS());
00800 
00801   Ops.Ty = E->getType();
00802   return Ops;
00803 }
00804 
00805 
00806 LValue ComplexExprEmitter::
00807 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
00808           ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
00809                          RValue &Val) {
00810   TestAndClearIgnoreReal();
00811   TestAndClearIgnoreImag();
00812   QualType LHSTy = E->getLHS()->getType();
00813 
00814   BinOpInfo OpInfo;
00815 
00816   // Load the RHS and LHS operands.
00817   // __block variables need to have the rhs evaluated first, plus this should
00818   // improve codegen a little.
00819   OpInfo.Ty = E->getComputationResultType();
00820   QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
00821 
00822   // The RHS should have been converted to the computation type.
00823   if (E->getRHS()->getType()->isRealFloatingType()) {
00824     assert(
00825         CGF.getContext()
00826             .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
00827     OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
00828   } else {
00829     assert(CGF.getContext()
00830                .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
00831     OpInfo.RHS = Visit(E->getRHS());
00832   }
00833 
00834   LValue LHS = CGF.EmitLValue(E->getLHS());
00835 
00836   // Load from the l-value and convert it.
00837   if (LHSTy->isAnyComplexType()) {
00838     ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, E->getExprLoc());
00839     OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty);
00840   } else {
00841     llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, E->getExprLoc());
00842     // For floating point real operands we can directly pass the scalar form
00843     // to the binary operator emission and potentially get more efficient code.
00844     if (LHSTy->isRealFloatingType()) {
00845       if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
00846         LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy);
00847       OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
00848     } else {
00849       OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty);
00850     }
00851   }
00852 
00853   // Expand the binary operator.
00854   ComplexPairTy Result = (this->*Func)(OpInfo);
00855 
00856   // Truncate the result and store it into the LHS lvalue.
00857   if (LHSTy->isAnyComplexType()) {
00858     ComplexPairTy ResVal = EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy);
00859     EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
00860     Val = RValue::getComplex(ResVal);
00861   } else {
00862     llvm::Value *ResVal =
00863         CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy);
00864     CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
00865     Val = RValue::get(ResVal);
00866   }
00867 
00868   return LHS;
00869 }
00870 
00871 // Compound assignments.
00872 ComplexPairTy ComplexExprEmitter::
00873 EmitCompoundAssign(const CompoundAssignOperator *E,
00874                    ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
00875   RValue Val;
00876   LValue LV = EmitCompoundAssignLValue(E, Func, Val);
00877 
00878   // The result of an assignment in C is the assigned r-value.
00879   if (!CGF.getLangOpts().CPlusPlus)
00880     return Val.getComplexVal();
00881 
00882   // If the lvalue is non-volatile, return the computed value of the assignment.
00883   if (!LV.isVolatileQualified())
00884     return Val.getComplexVal();
00885 
00886   return EmitLoadOfLValue(LV, E->getExprLoc());
00887 }
00888 
00889 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
00890                                                ComplexPairTy &Val) {
00891   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
00892                                                  E->getRHS()->getType()) &&
00893          "Invalid assignment");
00894   TestAndClearIgnoreReal();
00895   TestAndClearIgnoreImag();
00896 
00897   // Emit the RHS.  __block variables need the RHS evaluated first.
00898   Val = Visit(E->getRHS());
00899 
00900   // Compute the address to store into.
00901   LValue LHS = CGF.EmitLValue(E->getLHS());
00902 
00903   // Store the result value into the LHS lvalue.
00904   EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
00905 
00906   return LHS;
00907 }
00908 
00909 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
00910   ComplexPairTy Val;
00911   LValue LV = EmitBinAssignLValue(E, Val);
00912 
00913   // The result of an assignment in C is the assigned r-value.
00914   if (!CGF.getLangOpts().CPlusPlus)
00915     return Val;
00916 
00917   // If the lvalue is non-volatile, return the computed value of the assignment.
00918   if (!LV.isVolatileQualified())
00919     return Val;
00920 
00921   return EmitLoadOfLValue(LV, E->getExprLoc());
00922 }
00923 
00924 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
00925   CGF.EmitIgnoredExpr(E->getLHS());
00926   return Visit(E->getRHS());
00927 }
00928 
00929 ComplexPairTy ComplexExprEmitter::
00930 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
00931   TestAndClearIgnoreReal();
00932   TestAndClearIgnoreImag();
00933   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
00934   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
00935   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
00936 
00937   // Bind the common expression if necessary.
00938   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
00939 
00940   RegionCounter Cnt = CGF.getPGORegionCounter(E);
00941   CodeGenFunction::ConditionalEvaluation eval(CGF);
00942   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock, Cnt.getCount());
00943 
00944   eval.begin(CGF);
00945   CGF.EmitBlock(LHSBlock);
00946   Cnt.beginRegion(Builder);
00947   ComplexPairTy LHS = Visit(E->getTrueExpr());
00948   LHSBlock = Builder.GetInsertBlock();
00949   CGF.EmitBranch(ContBlock);
00950   eval.end(CGF);
00951 
00952   eval.begin(CGF);
00953   CGF.EmitBlock(RHSBlock);
00954   ComplexPairTy RHS = Visit(E->getFalseExpr());
00955   RHSBlock = Builder.GetInsertBlock();
00956   CGF.EmitBlock(ContBlock);
00957   eval.end(CGF);
00958 
00959   // Create a PHI node for the real part.
00960   llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
00961   RealPN->addIncoming(LHS.first, LHSBlock);
00962   RealPN->addIncoming(RHS.first, RHSBlock);
00963 
00964   // Create a PHI node for the imaginary part.
00965   llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
00966   ImagPN->addIncoming(LHS.second, LHSBlock);
00967   ImagPN->addIncoming(RHS.second, RHSBlock);
00968 
00969   return ComplexPairTy(RealPN, ImagPN);
00970 }
00971 
00972 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
00973   return Visit(E->getChosenSubExpr());
00974 }
00975 
00976 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
00977     bool Ignore = TestAndClearIgnoreReal();
00978     (void)Ignore;
00979     assert (Ignore == false && "init list ignored");
00980     Ignore = TestAndClearIgnoreImag();
00981     (void)Ignore;
00982     assert (Ignore == false && "init list ignored");
00983 
00984   if (E->getNumInits() == 2) {
00985     llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
00986     llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
00987     return ComplexPairTy(Real, Imag);
00988   } else if (E->getNumInits() == 1) {
00989     return Visit(E->getInit(0));
00990   }
00991 
00992   // Empty init list intializes to null
00993   assert(E->getNumInits() == 0 && "Unexpected number of inits");
00994   QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
00995   llvm::Type* LTy = CGF.ConvertType(Ty);
00996   llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
00997   return ComplexPairTy(zeroConstant, zeroConstant);
00998 }
00999 
01000 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
01001   llvm::Value *ArgValue = CGF.EmitVAListRef(E->getSubExpr());
01002   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, E->getType());
01003 
01004   if (!ArgPtr) {
01005     CGF.ErrorUnsupported(E, "complex va_arg expression");
01006     llvm::Type *EltTy =
01007       CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
01008     llvm::Value *U = llvm::UndefValue::get(EltTy);
01009     return ComplexPairTy(U, U);
01010   }
01011 
01012   return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(ArgPtr, E->getType()),
01013                           E->getExprLoc());
01014 }
01015 
01016 //===----------------------------------------------------------------------===//
01017 //                         Entry Point into this File
01018 //===----------------------------------------------------------------------===//
01019 
01020 /// EmitComplexExpr - Emit the computation of the specified expression of
01021 /// complex type, ignoring the result.
01022 ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E, bool IgnoreReal,
01023                                                bool IgnoreImag) {
01024   assert(E && getComplexType(E->getType()) &&
01025          "Invalid complex expression to emit");
01026 
01027   return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
01028     .Visit(const_cast<Expr*>(E));
01029 }
01030 
01031 void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,
01032                                                 bool isInit) {
01033   assert(E && getComplexType(E->getType()) &&
01034          "Invalid complex expression to emit");
01035   ComplexExprEmitter Emitter(*this);
01036   ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
01037   Emitter.EmitStoreOfComplex(Val, dest, isInit);
01038 }
01039 
01040 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
01041 void CodeGenFunction::EmitStoreOfComplex(ComplexPairTy V, LValue dest,
01042                                          bool isInit) {
01043   ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
01044 }
01045 
01046 /// EmitLoadOfComplex - Load a complex number from the specified address.
01047 ComplexPairTy CodeGenFunction::EmitLoadOfComplex(LValue src,
01048                                                  SourceLocation loc) {
01049   return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
01050 }
01051 
01052 LValue CodeGenFunction::EmitComplexAssignmentLValue(const BinaryOperator *E) {
01053   assert(E->getOpcode() == BO_Assign);
01054   ComplexPairTy Val; // ignored
01055   return ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
01056 }
01057 
01058 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
01059     const ComplexExprEmitter::BinOpInfo &);
01060 
01061 static CompoundFunc getComplexOp(BinaryOperatorKind Op) {
01062   switch (Op) {
01063   case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
01064   case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
01065   case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
01066   case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
01067   default:
01068     llvm_unreachable("unexpected complex compound assignment");
01069   }
01070 }
01071 
01072 LValue CodeGenFunction::
01073 EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E) {
01074   CompoundFunc Op = getComplexOp(E->getOpcode());
01075   RValue Val;
01076   return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
01077 }
01078 
01079 LValue CodeGenFunction::
01080 EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E,
01081                                      llvm::Value *&Result) {
01082   CompoundFunc Op = getComplexOp(E->getOpcode());
01083   RValue Val;
01084   LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
01085   Result = Val.getScalarVal();
01086   return Ret;
01087 }