xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGExprComplex.cpp (revision f976241773df2260e6170317080761d1c5814fe5)
1 //===--- CGExprComplex.cpp - Emit LLVM Code for Complex Exprs -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Expr nodes with complex types as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenFunction.h"
14 #include "CodeGenModule.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/MDBuilder.h"
20 #include "llvm/IR/Metadata.h"
21 #include <algorithm>
22 using namespace clang;
23 using namespace CodeGen;
24 
25 //===----------------------------------------------------------------------===//
26 //                        Complex Expression Emitter
27 //===----------------------------------------------------------------------===//
28 
29 typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
30 
31 /// Return the complex type that we are meant to emit.
32 static const ComplexType *getComplexType(QualType type) {
33   type = type.getCanonicalType();
34   if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
35     return comp;
36   } else {
37     return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
38   }
39 }
40 
41 namespace  {
42 class ComplexExprEmitter
43   : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
44   CodeGenFunction &CGF;
45   CGBuilderTy &Builder;
46   bool IgnoreReal;
47   bool IgnoreImag;
48 public:
49   ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
50     : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
51   }
52 
53 
54   //===--------------------------------------------------------------------===//
55   //                               Utilities
56   //===--------------------------------------------------------------------===//
57 
58   bool TestAndClearIgnoreReal() {
59     bool I = IgnoreReal;
60     IgnoreReal = false;
61     return I;
62   }
63   bool TestAndClearIgnoreImag() {
64     bool I = IgnoreImag;
65     IgnoreImag = false;
66     return I;
67   }
68 
69   /// EmitLoadOfLValue - Given an expression with complex type that represents a
70   /// value l-value, this method emits the address of the l-value, then loads
71   /// and returns the result.
72   ComplexPairTy EmitLoadOfLValue(const Expr *E) {
73     return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
74   }
75 
76   ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
77 
78   /// EmitStoreOfComplex - Store the specified real/imag parts into the
79   /// specified value pointer.
80   void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
81 
82   /// Emit a cast from complex value Val to DestType.
83   ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
84                                          QualType DestType, SourceLocation Loc);
85   /// Emit a cast from scalar value Val to DestType.
86   ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
87                                         QualType DestType, SourceLocation Loc);
88 
89   //===--------------------------------------------------------------------===//
90   //                            Visitor Methods
91   //===--------------------------------------------------------------------===//
92 
93   ComplexPairTy Visit(Expr *E) {
94     ApplyDebugLocation DL(CGF, E);
95     return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
96   }
97 
98   ComplexPairTy VisitStmt(Stmt *S) {
99     S->dump(CGF.getContext().getSourceManager());
100     llvm_unreachable("Stmt can't have complex result type!");
101   }
102   ComplexPairTy VisitExpr(Expr *S);
103   ComplexPairTy VisitConstantExpr(ConstantExpr *E) {
104     return Visit(E->getSubExpr());
105   }
106   ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
107   ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
108     return Visit(GE->getResultExpr());
109   }
110   ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
111   ComplexPairTy
112   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
113     return Visit(PE->getReplacement());
114   }
115   ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {
116     return CGF.EmitCoawaitExpr(*S).getComplexVal();
117   }
118   ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {
119     return CGF.EmitCoyieldExpr(*S).getComplexVal();
120   }
121   ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {
122     return Visit(E->getSubExpr());
123   }
124 
125   ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,
126                              Expr *E) {
127     assert(Constant && "not a constant");
128     if (Constant.isReference())
129       return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),
130                               E->getExprLoc());
131 
132     llvm::Constant *pair = Constant.getValue();
133     return ComplexPairTy(pair->getAggregateElement(0U),
134                          pair->getAggregateElement(1U));
135   }
136 
137   // l-values.
138   ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
139     if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
140       return emitConstant(Constant, E);
141     return EmitLoadOfLValue(E);
142   }
143   ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
144     return EmitLoadOfLValue(E);
145   }
146   ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
147     return CGF.EmitObjCMessageExpr(E).getComplexVal();
148   }
149   ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
150   ComplexPairTy VisitMemberExpr(MemberExpr *ME) {
151     if (CodeGenFunction::ConstantEmission Constant =
152             CGF.tryEmitAsConstant(ME)) {
153       CGF.EmitIgnoredExpr(ME->getBase());
154       return emitConstant(Constant, ME);
155     }
156     return EmitLoadOfLValue(ME);
157   }
158   ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
159     if (E->isGLValue())
160       return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
161                               E->getExprLoc());
162     return CGF.getOrCreateOpaqueRValueMapping(E).getComplexVal();
163   }
164 
165   ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
166     return CGF.EmitPseudoObjectRValue(E).getComplexVal();
167   }
168 
169   // FIXME: CompoundLiteralExpr
170 
171   ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
172   ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
173     // Unlike for scalars, we don't have to worry about function->ptr demotion
174     // here.
175     return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
176   }
177   ComplexPairTy VisitCastExpr(CastExpr *E) {
178     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
179       CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
180     return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
181   }
182   ComplexPairTy VisitCallExpr(const CallExpr *E);
183   ComplexPairTy VisitStmtExpr(const StmtExpr *E);
184 
185   // Operators.
186   ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
187                                    bool isInc, bool isPre) {
188     LValue LV = CGF.EmitLValue(E->getSubExpr());
189     return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
190   }
191   ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
192     return VisitPrePostIncDec(E, false, false);
193   }
194   ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
195     return VisitPrePostIncDec(E, true, false);
196   }
197   ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
198     return VisitPrePostIncDec(E, false, true);
199   }
200   ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
201     return VisitPrePostIncDec(E, true, true);
202   }
203   ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
204   ComplexPairTy VisitUnaryPlus     (const UnaryOperator *E) {
205     TestAndClearIgnoreReal();
206     TestAndClearIgnoreImag();
207     return Visit(E->getSubExpr());
208   }
209   ComplexPairTy VisitUnaryMinus    (const UnaryOperator *E);
210   ComplexPairTy VisitUnaryNot      (const UnaryOperator *E);
211   // LNot,Real,Imag never return complex.
212   ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
213     return Visit(E->getSubExpr());
214   }
215   ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
216     CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
217     return Visit(DAE->getExpr());
218   }
219   ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
220     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
221     return Visit(DIE->getExpr());
222   }
223   ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
224     CGF.enterFullExpression(E);
225     CodeGenFunction::RunCleanupsScope Scope(CGF);
226     ComplexPairTy Vals = Visit(E->getSubExpr());
227     // Defend against dominance problems caused by jumps out of expression
228     // evaluation through the shared cleanup block.
229     Scope.ForceCleanup({&Vals.first, &Vals.second});
230     return Vals;
231   }
232   ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
233     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
234     QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
235     llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
236     return ComplexPairTy(Null, Null);
237   }
238   ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
239     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
240     QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
241     llvm::Constant *Null =
242                        llvm::Constant::getNullValue(CGF.ConvertType(Elem));
243     return ComplexPairTy(Null, Null);
244   }
245 
246   struct BinOpInfo {
247     ComplexPairTy LHS;
248     ComplexPairTy RHS;
249     QualType Ty;  // Computation Type.
250   };
251 
252   BinOpInfo EmitBinOps(const BinaryOperator *E);
253   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
254                                   ComplexPairTy (ComplexExprEmitter::*Func)
255                                   (const BinOpInfo &),
256                                   RValue &Val);
257   ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,
258                                    ComplexPairTy (ComplexExprEmitter::*Func)
259                                    (const BinOpInfo &));
260 
261   ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
262   ComplexPairTy EmitBinSub(const BinOpInfo &Op);
263   ComplexPairTy EmitBinMul(const BinOpInfo &Op);
264   ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
265 
266   ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
267                                         const BinOpInfo &Op);
268 
269   ComplexPairTy VisitBinAdd(const BinaryOperator *E) {
270     return EmitBinAdd(EmitBinOps(E));
271   }
272   ComplexPairTy VisitBinSub(const BinaryOperator *E) {
273     return EmitBinSub(EmitBinOps(E));
274   }
275   ComplexPairTy VisitBinMul(const BinaryOperator *E) {
276     return EmitBinMul(EmitBinOps(E));
277   }
278   ComplexPairTy VisitBinDiv(const BinaryOperator *E) {
279     return EmitBinDiv(EmitBinOps(E));
280   }
281 
282   // Compound assignments.
283   ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
284     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
285   }
286   ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
287     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
288   }
289   ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
290     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
291   }
292   ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
293     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
294   }
295 
296   // GCC rejects rem/and/or/xor for integer complex.
297   // Logical and/or always return int, never complex.
298 
299   // No comparisons produce a complex result.
300 
301   LValue EmitBinAssignLValue(const BinaryOperator *E,
302                              ComplexPairTy &Val);
303   ComplexPairTy VisitBinAssign     (const BinaryOperator *E);
304   ComplexPairTy VisitBinComma      (const BinaryOperator *E);
305 
306 
307   ComplexPairTy
308   VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
309   ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
310 
311   ComplexPairTy VisitInitListExpr(InitListExpr *E);
312 
313   ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
314     return EmitLoadOfLValue(E);
315   }
316 
317   ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
318 
319   ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
320     return CGF.EmitAtomicExpr(E).getComplexVal();
321   }
322 };
323 }  // end anonymous namespace.
324 
325 //===----------------------------------------------------------------------===//
326 //                                Utilities
327 //===----------------------------------------------------------------------===//
328 
329 Address CodeGenFunction::emitAddrOfRealComponent(Address addr,
330                                                  QualType complexType) {
331   return Builder.CreateStructGEP(addr, 0, addr.getName() + ".realp");
332 }
333 
334 Address CodeGenFunction::emitAddrOfImagComponent(Address addr,
335                                                  QualType complexType) {
336   return Builder.CreateStructGEP(addr, 1, addr.getName() + ".imagp");
337 }
338 
339 /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
340 /// load the real and imaginary pieces, returning them as Real/Imag.
341 ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
342                                                    SourceLocation loc) {
343   assert(lvalue.isSimple() && "non-simple complex l-value?");
344   if (lvalue.getType()->isAtomicType())
345     return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
346 
347   Address SrcPtr = lvalue.getAddress();
348   bool isVolatile = lvalue.isVolatileQualified();
349 
350   llvm::Value *Real = nullptr, *Imag = nullptr;
351 
352   if (!IgnoreReal || isVolatile) {
353     Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
354     Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
355   }
356 
357   if (!IgnoreImag || isVolatile) {
358     Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
359     Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
360   }
361 
362   return ComplexPairTy(Real, Imag);
363 }
364 
365 /// EmitStoreOfComplex - Store the specified real/imag parts into the
366 /// specified value pointer.
367 void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
368                                             bool isInit) {
369   if (lvalue.getType()->isAtomicType() ||
370       (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
371     return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
372 
373   Address Ptr = lvalue.getAddress();
374   Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
375   Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
376 
377   Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
378   Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
379 }
380 
381 
382 
383 //===----------------------------------------------------------------------===//
384 //                            Visitor Methods
385 //===----------------------------------------------------------------------===//
386 
387 ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
388   CGF.ErrorUnsupported(E, "complex expression");
389   llvm::Type *EltTy =
390     CGF.ConvertType(getComplexType(E->getType())->getElementType());
391   llvm::Value *U = llvm::UndefValue::get(EltTy);
392   return ComplexPairTy(U, U);
393 }
394 
395 ComplexPairTy ComplexExprEmitter::
396 VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
397   llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
398   return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
399 }
400 
401 
402 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
403   if (E->getCallReturnType(CGF.getContext())->isReferenceType())
404     return EmitLoadOfLValue(E);
405 
406   return CGF.EmitCallExpr(E).getComplexVal();
407 }
408 
409 ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
410   CodeGenFunction::StmtExprEvaluation eval(CGF);
411   Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
412   assert(RetAlloca.isValid() && "Expected complex return value");
413   return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
414                           E->getExprLoc());
415 }
416 
417 /// Emit a cast from complex value Val to DestType.
418 ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
419                                                            QualType SrcType,
420                                                            QualType DestType,
421                                                            SourceLocation Loc) {
422   // Get the src/dest element type.
423   SrcType = SrcType->castAs<ComplexType>()->getElementType();
424   DestType = DestType->castAs<ComplexType>()->getElementType();
425 
426   // C99 6.3.1.6: When a value of complex type is converted to another
427   // complex type, both the real and imaginary parts follow the conversion
428   // rules for the corresponding real types.
429   Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
430   Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
431   return Val;
432 }
433 
434 ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
435                                                           QualType SrcType,
436                                                           QualType DestType,
437                                                           SourceLocation Loc) {
438   // Convert the input element to the element type of the complex.
439   DestType = DestType->castAs<ComplexType>()->getElementType();
440   Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
441 
442   // Return (realval, 0).
443   return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
444 }
445 
446 ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
447                                            QualType DestTy) {
448   switch (CK) {
449   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
450 
451   // Atomic to non-atomic casts may be more than a no-op for some platforms and
452   // for some types.
453   case CK_AtomicToNonAtomic:
454   case CK_NonAtomicToAtomic:
455   case CK_NoOp:
456   case CK_LValueToRValue:
457   case CK_UserDefinedConversion:
458     return Visit(Op);
459 
460   case CK_LValueBitCast: {
461     LValue origLV = CGF.EmitLValue(Op);
462     Address V = origLV.getAddress();
463     V = Builder.CreateElementBitCast(V, CGF.ConvertType(DestTy));
464     return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
465   }
466 
467   case CK_LValueToRValueBitCast: {
468     LValue SourceLVal = CGF.EmitLValue(Op);
469     Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(),
470                                                 CGF.ConvertTypeForMem(DestTy));
471     LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
472     DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
473     return EmitLoadOfLValue(DestLV, Op->getExprLoc());
474   }
475 
476   case CK_BitCast:
477   case CK_BaseToDerived:
478   case CK_DerivedToBase:
479   case CK_UncheckedDerivedToBase:
480   case CK_Dynamic:
481   case CK_ToUnion:
482   case CK_ArrayToPointerDecay:
483   case CK_FunctionToPointerDecay:
484   case CK_NullToPointer:
485   case CK_NullToMemberPointer:
486   case CK_BaseToDerivedMemberPointer:
487   case CK_DerivedToBaseMemberPointer:
488   case CK_MemberPointerToBoolean:
489   case CK_ReinterpretMemberPointer:
490   case CK_ConstructorConversion:
491   case CK_IntegralToPointer:
492   case CK_PointerToIntegral:
493   case CK_PointerToBoolean:
494   case CK_ToVoid:
495   case CK_VectorSplat:
496   case CK_IntegralCast:
497   case CK_BooleanToSignedIntegral:
498   case CK_IntegralToBoolean:
499   case CK_IntegralToFloating:
500   case CK_FloatingToIntegral:
501   case CK_FloatingToBoolean:
502   case CK_FloatingCast:
503   case CK_CPointerToObjCPointerCast:
504   case CK_BlockPointerToObjCPointerCast:
505   case CK_AnyPointerToBlockPointerCast:
506   case CK_ObjCObjectLValueCast:
507   case CK_FloatingComplexToReal:
508   case CK_FloatingComplexToBoolean:
509   case CK_IntegralComplexToReal:
510   case CK_IntegralComplexToBoolean:
511   case CK_ARCProduceObject:
512   case CK_ARCConsumeObject:
513   case CK_ARCReclaimReturnedObject:
514   case CK_ARCExtendBlockObject:
515   case CK_CopyAndAutoreleaseBlockObject:
516   case CK_BuiltinFnToFnPtr:
517   case CK_ZeroToOCLOpaqueType:
518   case CK_AddressSpaceConversion:
519   case CK_IntToOCLSampler:
520   case CK_FixedPointCast:
521   case CK_FixedPointToBoolean:
522   case CK_FixedPointToIntegral:
523   case CK_IntegralToFixedPoint:
524     llvm_unreachable("invalid cast kind for complex value");
525 
526   case CK_FloatingRealToComplex:
527   case CK_IntegralRealToComplex:
528     return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
529                                    DestTy, Op->getExprLoc());
530 
531   case CK_FloatingComplexCast:
532   case CK_FloatingComplexToIntegralComplex:
533   case CK_IntegralComplexCast:
534   case CK_IntegralComplexToFloatingComplex:
535     return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
536                                     Op->getExprLoc());
537   }
538 
539   llvm_unreachable("unknown cast resulting in complex value");
540 }
541 
542 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
543   TestAndClearIgnoreReal();
544   TestAndClearIgnoreImag();
545   ComplexPairTy Op = Visit(E->getSubExpr());
546 
547   llvm::Value *ResR, *ResI;
548   if (Op.first->getType()->isFloatingPointTy()) {
549     ResR = Builder.CreateFNeg(Op.first,  "neg.r");
550     ResI = Builder.CreateFNeg(Op.second, "neg.i");
551   } else {
552     ResR = Builder.CreateNeg(Op.first,  "neg.r");
553     ResI = Builder.CreateNeg(Op.second, "neg.i");
554   }
555   return ComplexPairTy(ResR, ResI);
556 }
557 
558 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
559   TestAndClearIgnoreReal();
560   TestAndClearIgnoreImag();
561   // ~(a+ib) = a + i*-b
562   ComplexPairTy Op = Visit(E->getSubExpr());
563   llvm::Value *ResI;
564   if (Op.second->getType()->isFloatingPointTy())
565     ResI = Builder.CreateFNeg(Op.second, "conj.i");
566   else
567     ResI = Builder.CreateNeg(Op.second, "conj.i");
568 
569   return ComplexPairTy(Op.first, ResI);
570 }
571 
572 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
573   llvm::Value *ResR, *ResI;
574 
575   if (Op.LHS.first->getType()->isFloatingPointTy()) {
576     ResR = Builder.CreateFAdd(Op.LHS.first,  Op.RHS.first,  "add.r");
577     if (Op.LHS.second && Op.RHS.second)
578       ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
579     else
580       ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
581     assert(ResI && "Only one operand may be real!");
582   } else {
583     ResR = Builder.CreateAdd(Op.LHS.first,  Op.RHS.first,  "add.r");
584     assert(Op.LHS.second && Op.RHS.second &&
585            "Both operands of integer complex operators must be complex!");
586     ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
587   }
588   return ComplexPairTy(ResR, ResI);
589 }
590 
591 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
592   llvm::Value *ResR, *ResI;
593   if (Op.LHS.first->getType()->isFloatingPointTy()) {
594     ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
595     if (Op.LHS.second && Op.RHS.second)
596       ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
597     else
598       ResI = Op.LHS.second ? Op.LHS.second
599                            : Builder.CreateFNeg(Op.RHS.second, "sub.i");
600     assert(ResI && "Only one operand may be real!");
601   } else {
602     ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
603     assert(Op.LHS.second && Op.RHS.second &&
604            "Both operands of integer complex operators must be complex!");
605     ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
606   }
607   return ComplexPairTy(ResR, ResI);
608 }
609 
610 /// Emit a libcall for a binary operation on complex types.
611 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
612                                                           const BinOpInfo &Op) {
613   CallArgList Args;
614   Args.add(RValue::get(Op.LHS.first),
615            Op.Ty->castAs<ComplexType>()->getElementType());
616   Args.add(RValue::get(Op.LHS.second),
617            Op.Ty->castAs<ComplexType>()->getElementType());
618   Args.add(RValue::get(Op.RHS.first),
619            Op.Ty->castAs<ComplexType>()->getElementType());
620   Args.add(RValue::get(Op.RHS.second),
621            Op.Ty->castAs<ComplexType>()->getElementType());
622 
623   // We *must* use the full CG function call building logic here because the
624   // complex type has special ABI handling. We also should not forget about
625   // special calling convention which may be used for compiler builtins.
626 
627   // We create a function qualified type to state that this call does not have
628   // any exceptions.
629   FunctionProtoType::ExtProtoInfo EPI;
630   EPI = EPI.withExceptionSpec(
631       FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));
632   SmallVector<QualType, 4> ArgsQTys(
633       4, Op.Ty->castAs<ComplexType>()->getElementType());
634   QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
635   const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
636       Args, cast<FunctionType>(FQTy.getTypePtr()), false);
637 
638   llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
639   llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(
640       FTy, LibCallName, llvm::AttributeList(), true);
641   CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
642 
643   llvm::CallBase *Call;
644   RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
645   Call->setCallingConv(CGF.CGM.getRuntimeCC());
646   return Res.getComplexVal();
647 }
648 
649 /// Lookup the libcall name for a given floating point type complex
650 /// multiply.
651 static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
652   switch (Ty->getTypeID()) {
653   default:
654     llvm_unreachable("Unsupported floating point type!");
655   case llvm::Type::HalfTyID:
656     return "__mulhc3";
657   case llvm::Type::FloatTyID:
658     return "__mulsc3";
659   case llvm::Type::DoubleTyID:
660     return "__muldc3";
661   case llvm::Type::PPC_FP128TyID:
662     return "__multc3";
663   case llvm::Type::X86_FP80TyID:
664     return "__mulxc3";
665   case llvm::Type::FP128TyID:
666     return "__multc3";
667   }
668 }
669 
670 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
671 // typed values.
672 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
673   using llvm::Value;
674   Value *ResR, *ResI;
675   llvm::MDBuilder MDHelper(CGF.getLLVMContext());
676 
677   if (Op.LHS.first->getType()->isFloatingPointTy()) {
678     // The general formulation is:
679     // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
680     //
681     // But we can fold away components which would be zero due to a real
682     // operand according to C11 Annex G.5.1p2.
683     // FIXME: C11 also provides for imaginary types which would allow folding
684     // still more of this within the type system.
685 
686     if (Op.LHS.second && Op.RHS.second) {
687       // If both operands are complex, emit the core math directly, and then
688       // test for NaNs. If we find NaNs in the result, we delegate to a libcall
689       // to carefully re-compute the correct infinity representation if
690       // possible. The expectation is that the presence of NaNs here is
691       // *extremely* rare, and so the cost of the libcall is almost irrelevant.
692       // This is good, because the libcall re-computes the core multiplication
693       // exactly the same as we do here and re-tests for NaNs in order to be
694       // a generic complex*complex libcall.
695 
696       // First compute the four products.
697       Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
698       Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
699       Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
700       Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
701 
702       // The real part is the difference of the first two, the imaginary part is
703       // the sum of the second.
704       ResR = Builder.CreateFSub(AC, BD, "mul_r");
705       ResI = Builder.CreateFAdd(AD, BC, "mul_i");
706 
707       // Emit the test for the real part becoming NaN and create a branch to
708       // handle it. We test for NaN by comparing the number to itself.
709       Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
710       llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
711       llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
712       llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
713       llvm::BasicBlock *OrigBB = Branch->getParent();
714 
715       // Give hint that we very much don't expect to see NaNs.
716       // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
717       llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
718       Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
719 
720       // Now test the imaginary part and create its branch.
721       CGF.EmitBlock(INaNBB);
722       Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
723       llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
724       Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
725       Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
726 
727       // Now emit the libcall on this slowest of the slow paths.
728       CGF.EmitBlock(LibCallBB);
729       Value *LibCallR, *LibCallI;
730       std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
731           getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
732       Builder.CreateBr(ContBB);
733 
734       // Finally continue execution by phi-ing together the different
735       // computation paths.
736       CGF.EmitBlock(ContBB);
737       llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
738       RealPHI->addIncoming(ResR, OrigBB);
739       RealPHI->addIncoming(ResR, INaNBB);
740       RealPHI->addIncoming(LibCallR, LibCallBB);
741       llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
742       ImagPHI->addIncoming(ResI, OrigBB);
743       ImagPHI->addIncoming(ResI, INaNBB);
744       ImagPHI->addIncoming(LibCallI, LibCallBB);
745       return ComplexPairTy(RealPHI, ImagPHI);
746     }
747     assert((Op.LHS.second || Op.RHS.second) &&
748            "At least one operand must be complex!");
749 
750     // If either of the operands is a real rather than a complex, the
751     // imaginary component is ignored when computing the real component of the
752     // result.
753     ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
754 
755     ResI = Op.LHS.second
756                ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
757                : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
758   } else {
759     assert(Op.LHS.second && Op.RHS.second &&
760            "Both operands of integer complex operators must be complex!");
761     Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
762     Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
763     ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
764 
765     Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
766     Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
767     ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
768   }
769   return ComplexPairTy(ResR, ResI);
770 }
771 
772 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
773 // typed values.
774 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
775   llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
776   llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
777 
778   llvm::Value *DSTr, *DSTi;
779   if (LHSr->getType()->isFloatingPointTy()) {
780     // If we have a complex operand on the RHS and FastMath is not allowed, we
781     // delegate to a libcall to handle all of the complexities and minimize
782     // underflow/overflow cases. When FastMath is allowed we construct the
783     // divide inline using the same algorithm as for integer operands.
784     //
785     // FIXME: We would be able to avoid the libcall in many places if we
786     // supported imaginary types in addition to complex types.
787     if (RHSi && !CGF.getLangOpts().FastMath) {
788       BinOpInfo LibCallOp = Op;
789       // If LHS was a real, supply a null imaginary part.
790       if (!LHSi)
791         LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
792 
793       switch (LHSr->getType()->getTypeID()) {
794       default:
795         llvm_unreachable("Unsupported floating point type!");
796       case llvm::Type::HalfTyID:
797         return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
798       case llvm::Type::FloatTyID:
799         return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
800       case llvm::Type::DoubleTyID:
801         return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
802       case llvm::Type::PPC_FP128TyID:
803         return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
804       case llvm::Type::X86_FP80TyID:
805         return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
806       case llvm::Type::FP128TyID:
807         return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
808       }
809     } else if (RHSi) {
810       if (!LHSi)
811         LHSi = llvm::Constant::getNullValue(RHSi->getType());
812 
813       // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
814       llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
815       llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
816       llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
817 
818       llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
819       llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
820       llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
821 
822       llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
823       llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
824       llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
825 
826       DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
827       DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
828     } else {
829       assert(LHSi && "Can have at most one non-complex operand!");
830 
831       DSTr = Builder.CreateFDiv(LHSr, RHSr);
832       DSTi = Builder.CreateFDiv(LHSi, RHSr);
833     }
834   } else {
835     assert(Op.LHS.second && Op.RHS.second &&
836            "Both operands of integer complex operators must be complex!");
837     // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
838     llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
839     llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
840     llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
841 
842     llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
843     llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
844     llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
845 
846     llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
847     llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
848     llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
849 
850     if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
851       DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
852       DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
853     } else {
854       DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
855       DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
856     }
857   }
858 
859   return ComplexPairTy(DSTr, DSTi);
860 }
861 
862 ComplexExprEmitter::BinOpInfo
863 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
864   TestAndClearIgnoreReal();
865   TestAndClearIgnoreImag();
866   BinOpInfo Ops;
867   if (E->getLHS()->getType()->isRealFloatingType())
868     Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
869   else
870     Ops.LHS = Visit(E->getLHS());
871   if (E->getRHS()->getType()->isRealFloatingType())
872     Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
873   else
874     Ops.RHS = Visit(E->getRHS());
875 
876   Ops.Ty = E->getType();
877   return Ops;
878 }
879 
880 
881 LValue ComplexExprEmitter::
882 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
883           ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
884                          RValue &Val) {
885   TestAndClearIgnoreReal();
886   TestAndClearIgnoreImag();
887   QualType LHSTy = E->getLHS()->getType();
888   if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
889     LHSTy = AT->getValueType();
890 
891   BinOpInfo OpInfo;
892 
893   // Load the RHS and LHS operands.
894   // __block variables need to have the rhs evaluated first, plus this should
895   // improve codegen a little.
896   OpInfo.Ty = E->getComputationResultType();
897   QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
898 
899   // The RHS should have been converted to the computation type.
900   if (E->getRHS()->getType()->isRealFloatingType()) {
901     assert(
902         CGF.getContext()
903             .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
904     OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
905   } else {
906     assert(CGF.getContext()
907                .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
908     OpInfo.RHS = Visit(E->getRHS());
909   }
910 
911   LValue LHS = CGF.EmitLValue(E->getLHS());
912 
913   // Load from the l-value and convert it.
914   SourceLocation Loc = E->getExprLoc();
915   if (LHSTy->isAnyComplexType()) {
916     ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
917     OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
918   } else {
919     llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
920     // For floating point real operands we can directly pass the scalar form
921     // to the binary operator emission and potentially get more efficient code.
922     if (LHSTy->isRealFloatingType()) {
923       if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
924         LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
925       OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
926     } else {
927       OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
928     }
929   }
930 
931   // Expand the binary operator.
932   ComplexPairTy Result = (this->*Func)(OpInfo);
933 
934   // Truncate the result and store it into the LHS lvalue.
935   if (LHSTy->isAnyComplexType()) {
936     ComplexPairTy ResVal =
937         EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
938     EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
939     Val = RValue::getComplex(ResVal);
940   } else {
941     llvm::Value *ResVal =
942         CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
943     CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
944     Val = RValue::get(ResVal);
945   }
946 
947   return LHS;
948 }
949 
950 // Compound assignments.
951 ComplexPairTy ComplexExprEmitter::
952 EmitCompoundAssign(const CompoundAssignOperator *E,
953                    ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
954   RValue Val;
955   LValue LV = EmitCompoundAssignLValue(E, Func, Val);
956 
957   // The result of an assignment in C is the assigned r-value.
958   if (!CGF.getLangOpts().CPlusPlus)
959     return Val.getComplexVal();
960 
961   // If the lvalue is non-volatile, return the computed value of the assignment.
962   if (!LV.isVolatileQualified())
963     return Val.getComplexVal();
964 
965   return EmitLoadOfLValue(LV, E->getExprLoc());
966 }
967 
968 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
969                                                ComplexPairTy &Val) {
970   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
971                                                  E->getRHS()->getType()) &&
972          "Invalid assignment");
973   TestAndClearIgnoreReal();
974   TestAndClearIgnoreImag();
975 
976   // Emit the RHS.  __block variables need the RHS evaluated first.
977   Val = Visit(E->getRHS());
978 
979   // Compute the address to store into.
980   LValue LHS = CGF.EmitLValue(E->getLHS());
981 
982   // Store the result value into the LHS lvalue.
983   EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
984 
985   return LHS;
986 }
987 
988 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
989   ComplexPairTy Val;
990   LValue LV = EmitBinAssignLValue(E, Val);
991 
992   // The result of an assignment in C is the assigned r-value.
993   if (!CGF.getLangOpts().CPlusPlus)
994     return Val;
995 
996   // If the lvalue is non-volatile, return the computed value of the assignment.
997   if (!LV.isVolatileQualified())
998     return Val;
999 
1000   return EmitLoadOfLValue(LV, E->getExprLoc());
1001 }
1002 
1003 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
1004   CGF.EmitIgnoredExpr(E->getLHS());
1005   return Visit(E->getRHS());
1006 }
1007 
1008 ComplexPairTy ComplexExprEmitter::
1009 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1010   TestAndClearIgnoreReal();
1011   TestAndClearIgnoreImag();
1012   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1013   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1014   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1015 
1016   // Bind the common expression if necessary.
1017   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1018 
1019 
1020   CodeGenFunction::ConditionalEvaluation eval(CGF);
1021   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1022                            CGF.getProfileCount(E));
1023 
1024   eval.begin(CGF);
1025   CGF.EmitBlock(LHSBlock);
1026   CGF.incrementProfileCounter(E);
1027   ComplexPairTy LHS = Visit(E->getTrueExpr());
1028   LHSBlock = Builder.GetInsertBlock();
1029   CGF.EmitBranch(ContBlock);
1030   eval.end(CGF);
1031 
1032   eval.begin(CGF);
1033   CGF.EmitBlock(RHSBlock);
1034   ComplexPairTy RHS = Visit(E->getFalseExpr());
1035   RHSBlock = Builder.GetInsertBlock();
1036   CGF.EmitBlock(ContBlock);
1037   eval.end(CGF);
1038 
1039   // Create a PHI node for the real part.
1040   llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1041   RealPN->addIncoming(LHS.first, LHSBlock);
1042   RealPN->addIncoming(RHS.first, RHSBlock);
1043 
1044   // Create a PHI node for the imaginary part.
1045   llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1046   ImagPN->addIncoming(LHS.second, LHSBlock);
1047   ImagPN->addIncoming(RHS.second, RHSBlock);
1048 
1049   return ComplexPairTy(RealPN, ImagPN);
1050 }
1051 
1052 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1053   return Visit(E->getChosenSubExpr());
1054 }
1055 
1056 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1057     bool Ignore = TestAndClearIgnoreReal();
1058     (void)Ignore;
1059     assert (Ignore == false && "init list ignored");
1060     Ignore = TestAndClearIgnoreImag();
1061     (void)Ignore;
1062     assert (Ignore == false && "init list ignored");
1063 
1064   if (E->getNumInits() == 2) {
1065     llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1066     llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1067     return ComplexPairTy(Real, Imag);
1068   } else if (E->getNumInits() == 1) {
1069     return Visit(E->getInit(0));
1070   }
1071 
1072   // Empty init list initializes to null
1073   assert(E->getNumInits() == 0 && "Unexpected number of inits");
1074   QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1075   llvm::Type* LTy = CGF.ConvertType(Ty);
1076   llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
1077   return ComplexPairTy(zeroConstant, zeroConstant);
1078 }
1079 
1080 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1081   Address ArgValue = Address::invalid();
1082   Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
1083 
1084   if (!ArgPtr.isValid()) {
1085     CGF.ErrorUnsupported(E, "complex va_arg expression");
1086     llvm::Type *EltTy =
1087       CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1088     llvm::Value *U = llvm::UndefValue::get(EltTy);
1089     return ComplexPairTy(U, U);
1090   }
1091 
1092   return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
1093                           E->getExprLoc());
1094 }
1095 
1096 //===----------------------------------------------------------------------===//
1097 //                         Entry Point into this File
1098 //===----------------------------------------------------------------------===//
1099 
1100 /// EmitComplexExpr - Emit the computation of the specified expression of
1101 /// complex type, ignoring the result.
1102 ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E, bool IgnoreReal,
1103                                                bool IgnoreImag) {
1104   assert(E && getComplexType(E->getType()) &&
1105          "Invalid complex expression to emit");
1106 
1107   return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1108       .Visit(const_cast<Expr *>(E));
1109 }
1110 
1111 void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,
1112                                                 bool isInit) {
1113   assert(E && getComplexType(E->getType()) &&
1114          "Invalid complex expression to emit");
1115   ComplexExprEmitter Emitter(*this);
1116   ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
1117   Emitter.EmitStoreOfComplex(Val, dest, isInit);
1118 }
1119 
1120 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
1121 void CodeGenFunction::EmitStoreOfComplex(ComplexPairTy V, LValue dest,
1122                                          bool isInit) {
1123   ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1124 }
1125 
1126 /// EmitLoadOfComplex - Load a complex number from the specified address.
1127 ComplexPairTy CodeGenFunction::EmitLoadOfComplex(LValue src,
1128                                                  SourceLocation loc) {
1129   return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1130 }
1131 
1132 LValue CodeGenFunction::EmitComplexAssignmentLValue(const BinaryOperator *E) {
1133   assert(E->getOpcode() == BO_Assign);
1134   ComplexPairTy Val; // ignored
1135   return ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1136 }
1137 
1138 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1139     const ComplexExprEmitter::BinOpInfo &);
1140 
1141 static CompoundFunc getComplexOp(BinaryOperatorKind Op) {
1142   switch (Op) {
1143   case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
1144   case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
1145   case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
1146   case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
1147   default:
1148     llvm_unreachable("unexpected complex compound assignment");
1149   }
1150 }
1151 
1152 LValue CodeGenFunction::
1153 EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E) {
1154   CompoundFunc Op = getComplexOp(E->getOpcode());
1155   RValue Val;
1156   return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1157 }
1158 
1159 LValue CodeGenFunction::
1160 EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
1161                                     llvm::Value *&Result) {
1162   CompoundFunc Op = getComplexOp(E->getOpcode());
1163   RValue Val;
1164   LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1165   Result = Val.getScalarVal();
1166   return Ret;
1167 }
1168