clang  8.0.0svn
CGExprComplex.cpp
Go to the documentation of this file.
1 //===--- CGExprComplex.cpp - Emit LLVM Code for Complex Exprs -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Expr nodes with complex types as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/MDBuilder.h"
21 #include "llvm/IR/Metadata.h"
22 #include <algorithm>
23 using namespace clang;
24 using namespace CodeGen;
25 
26 //===----------------------------------------------------------------------===//
27 // Complex Expression Emitter
28 //===----------------------------------------------------------------------===//
29 
31 
32 /// Return the complex type that we are meant to emit.
34  type = type.getCanonicalType();
35  if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
36  return comp;
37  } else {
38  return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
39  }
40 }
41 
42 namespace {
43 class ComplexExprEmitter
44  : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
45  CodeGenFunction &CGF;
46  CGBuilderTy &Builder;
47  bool IgnoreReal;
48  bool IgnoreImag;
49 public:
50  ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
51  : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
52  }
53 
54 
55  //===--------------------------------------------------------------------===//
56  // Utilities
57  //===--------------------------------------------------------------------===//
58 
59  bool TestAndClearIgnoreReal() {
60  bool I = IgnoreReal;
61  IgnoreReal = false;
62  return I;
63  }
64  bool TestAndClearIgnoreImag() {
65  bool I = IgnoreImag;
66  IgnoreImag = false;
67  return I;
68  }
69 
70  /// EmitLoadOfLValue - Given an expression with complex type that represents a
71  /// value l-value, this method emits the address of the l-value, then loads
72  /// and returns the result.
73  ComplexPairTy EmitLoadOfLValue(const Expr *E) {
74  return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
75  }
76 
77  ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
78 
79  /// EmitStoreOfComplex - Store the specified real/imag parts into the
80  /// specified value pointer.
81  void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
82 
83  /// Emit a cast from complex value Val to DestType.
84  ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
85  QualType DestType, SourceLocation Loc);
86  /// Emit a cast from scalar value Val to DestType.
87  ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
88  QualType DestType, SourceLocation Loc);
89 
90  //===--------------------------------------------------------------------===//
91  // Visitor Methods
92  //===--------------------------------------------------------------------===//
93 
94  ComplexPairTy Visit(Expr *E) {
95  ApplyDebugLocation DL(CGF, E);
97  }
98 
99  ComplexPairTy VisitStmt(Stmt *S) {
100  S->dump(CGF.getContext().getSourceManager());
101  llvm_unreachable("Stmt can't have complex result type!");
102  }
103  ComplexPairTy VisitExpr(Expr *S);
104  ComplexPairTy VisitConstantExpr(ConstantExpr *E) {
105  return Visit(E->getSubExpr());
106  }
107  ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
108  ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
109  return Visit(GE->getResultExpr());
110  }
111  ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
113  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
114  return Visit(PE->getReplacement());
115  }
116  ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {
117  return CGF.EmitCoawaitExpr(*S).getComplexVal();
118  }
119  ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {
120  return CGF.EmitCoyieldExpr(*S).getComplexVal();
121  }
122  ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {
123  return Visit(E->getSubExpr());
124  }
125 
126  ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,
127  Expr *E) {
128  assert(Constant && "not a constant");
129  if (Constant.isReference())
130  return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),
131  E->getExprLoc());
132 
133  llvm::Constant *pair = Constant.getValue();
134  return ComplexPairTy(pair->getAggregateElement(0U),
135  pair->getAggregateElement(1U));
136  }
137 
138  // l-values.
139  ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
140  if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
141  return emitConstant(Constant, E);
142  return EmitLoadOfLValue(E);
143  }
144  ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
145  return EmitLoadOfLValue(E);
146  }
147  ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
148  return CGF.EmitObjCMessageExpr(E).getComplexVal();
149  }
150  ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
151  ComplexPairTy VisitMemberExpr(MemberExpr *ME) {
152  if (CodeGenFunction::ConstantEmission Constant =
153  CGF.tryEmitAsConstant(ME)) {
154  CGF.EmitIgnoredExpr(ME->getBase());
155  return emitConstant(Constant, ME);
156  }
157  return EmitLoadOfLValue(ME);
158  }
159  ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
160  if (E->isGLValue())
161  return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
162  E->getExprLoc());
163  return CGF.getOrCreateOpaqueRValueMapping(E).getComplexVal();
164  }
165 
166  ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
167  return CGF.EmitPseudoObjectRValue(E).getComplexVal();
168  }
169 
170  // FIXME: CompoundLiteralExpr
171 
172  ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
173  ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
174  // Unlike for scalars, we don't have to worry about function->ptr demotion
175  // here.
176  return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
177  }
178  ComplexPairTy VisitCastExpr(CastExpr *E) {
179  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
180  CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
181  return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
182  }
183  ComplexPairTy VisitCallExpr(const CallExpr *E);
184  ComplexPairTy VisitStmtExpr(const StmtExpr *E);
185 
186  // Operators.
187  ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
188  bool isInc, bool isPre) {
189  LValue LV = CGF.EmitLValue(E->getSubExpr());
190  return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
191  }
192  ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
193  return VisitPrePostIncDec(E, false, false);
194  }
195  ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
196  return VisitPrePostIncDec(E, true, false);
197  }
198  ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
199  return VisitPrePostIncDec(E, false, true);
200  }
201  ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
202  return VisitPrePostIncDec(E, true, true);
203  }
204  ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
205  ComplexPairTy VisitUnaryPlus (const UnaryOperator *E) {
206  TestAndClearIgnoreReal();
207  TestAndClearIgnoreImag();
208  return Visit(E->getSubExpr());
209  }
210  ComplexPairTy VisitUnaryMinus (const UnaryOperator *E);
211  ComplexPairTy VisitUnaryNot (const UnaryOperator *E);
212  // LNot,Real,Imag never return complex.
213  ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
214  return Visit(E->getSubExpr());
215  }
216  ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
217  return Visit(DAE->getExpr());
218  }
219  ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
221  return Visit(DIE->getExpr());
222  }
223  ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
224  CGF.enterFullExpression(E);
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 
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 
331  CharUnits offset = CharUnits::Zero();
332  return Builder.CreateStructGEP(addr, 0, offset, addr.getName() + ".realp");
333 }
334 
337  QualType eltType = complexType->castAs<ComplexType>()->getElementType();
338  CharUnits offset = getContext().getTypeSizeInChars(eltType);
339  return Builder.CreateStructGEP(addr, 1, offset, addr.getName() + ".imagp");
340 }
341 
342 /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
343 /// load the real and imaginary pieces, returning them as Real/Imag.
344 ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
345  SourceLocation loc) {
346  assert(lvalue.isSimple() && "non-simple complex l-value?");
347  if (lvalue.getType()->isAtomicType())
348  return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
349 
350  Address SrcPtr = lvalue.getAddress();
351  bool isVolatile = lvalue.isVolatileQualified();
352 
353  llvm::Value *Real = nullptr, *Imag = nullptr;
354 
355  if (!IgnoreReal || isVolatile) {
356  Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
357  Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
358  }
359 
360  if (!IgnoreImag || isVolatile) {
361  Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
362  Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
363  }
364 
365  return ComplexPairTy(Real, Imag);
366 }
367 
368 /// EmitStoreOfComplex - Store the specified real/imag parts into the
369 /// specified value pointer.
370 void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
371  bool isInit) {
372  if (lvalue.getType()->isAtomicType() ||
373  (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
374  return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
375 
376  Address Ptr = lvalue.getAddress();
377  Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
378  Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
379 
380  Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
381  Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
382 }
383 
384 
385 
386 //===----------------------------------------------------------------------===//
387 // Visitor Methods
388 //===----------------------------------------------------------------------===//
389 
390 ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
391  CGF.ErrorUnsupported(E, "complex expression");
392  llvm::Type *EltTy =
393  CGF.ConvertType(getComplexType(E->getType())->getElementType());
394  llvm::Value *U = llvm::UndefValue::get(EltTy);
395  return ComplexPairTy(U, U);
396 }
397 
398 ComplexPairTy ComplexExprEmitter::
399 VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
400  llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
401  return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
402 }
403 
404 
405 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
406  if (E->getCallReturnType(CGF.getContext())->isReferenceType())
407  return EmitLoadOfLValue(E);
408 
409  return CGF.EmitCallExpr(E).getComplexVal();
410 }
411 
412 ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
414  Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
415  assert(RetAlloca.isValid() && "Expected complex return value");
416  return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
417  E->getExprLoc());
418 }
419 
420 /// Emit a cast from complex value Val to DestType.
421 ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
422  QualType SrcType,
423  QualType DestType,
424  SourceLocation Loc) {
425  // Get the src/dest element type.
426  SrcType = SrcType->castAs<ComplexType>()->getElementType();
427  DestType = DestType->castAs<ComplexType>()->getElementType();
428 
429  // C99 6.3.1.6: When a value of complex type is converted to another
430  // complex type, both the real and imaginary parts follow the conversion
431  // rules for the corresponding real types.
432  Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
433  Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
434  return Val;
435 }
436 
437 ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
438  QualType SrcType,
439  QualType DestType,
440  SourceLocation Loc) {
441  // Convert the input element to the element type of the complex.
442  DestType = DestType->castAs<ComplexType>()->getElementType();
443  Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
444 
445  // Return (realval, 0).
446  return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
447 }
448 
449 ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
450  QualType DestTy) {
451  switch (CK) {
452  case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
453 
454  // Atomic to non-atomic casts may be more than a no-op for some platforms and
455  // for some types.
456  case CK_AtomicToNonAtomic:
457  case CK_NonAtomicToAtomic:
458  case CK_NoOp:
459  case CK_LValueToRValue:
460  case CK_UserDefinedConversion:
461  return Visit(Op);
462 
463  case CK_LValueBitCast: {
464  LValue origLV = CGF.EmitLValue(Op);
465  Address V = origLV.getAddress();
466  V = Builder.CreateElementBitCast(V, CGF.ConvertType(DestTy));
467  return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
468  }
469 
470  case CK_BitCast:
471  case CK_BaseToDerived:
472  case CK_DerivedToBase:
473  case CK_UncheckedDerivedToBase:
474  case CK_Dynamic:
475  case CK_ToUnion:
476  case CK_ArrayToPointerDecay:
477  case CK_FunctionToPointerDecay:
478  case CK_NullToPointer:
479  case CK_NullToMemberPointer:
480  case CK_BaseToDerivedMemberPointer:
481  case CK_DerivedToBaseMemberPointer:
482  case CK_MemberPointerToBoolean:
483  case CK_ReinterpretMemberPointer:
484  case CK_ConstructorConversion:
485  case CK_IntegralToPointer:
486  case CK_PointerToIntegral:
487  case CK_PointerToBoolean:
488  case CK_ToVoid:
489  case CK_VectorSplat:
490  case CK_IntegralCast:
491  case CK_BooleanToSignedIntegral:
492  case CK_IntegralToBoolean:
493  case CK_IntegralToFloating:
494  case CK_FloatingToIntegral:
495  case CK_FloatingToBoolean:
496  case CK_FloatingCast:
497  case CK_CPointerToObjCPointerCast:
498  case CK_BlockPointerToObjCPointerCast:
499  case CK_AnyPointerToBlockPointerCast:
500  case CK_ObjCObjectLValueCast:
501  case CK_FloatingComplexToReal:
502  case CK_FloatingComplexToBoolean:
503  case CK_IntegralComplexToReal:
504  case CK_IntegralComplexToBoolean:
505  case CK_ARCProduceObject:
506  case CK_ARCConsumeObject:
507  case CK_ARCReclaimReturnedObject:
508  case CK_ARCExtendBlockObject:
509  case CK_CopyAndAutoreleaseBlockObject:
510  case CK_BuiltinFnToFnPtr:
511  case CK_ZeroToOCLOpaqueType:
512  case CK_AddressSpaceConversion:
513  case CK_IntToOCLSampler:
514  case CK_FixedPointCast:
515  case CK_FixedPointToBoolean:
516  llvm_unreachable("invalid cast kind for complex value");
517 
518  case CK_FloatingRealToComplex:
519  case CK_IntegralRealToComplex:
520  return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
521  DestTy, Op->getExprLoc());
522 
523  case CK_FloatingComplexCast:
524  case CK_FloatingComplexToIntegralComplex:
525  case CK_IntegralComplexCast:
526  case CK_IntegralComplexToFloatingComplex:
527  return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
528  Op->getExprLoc());
529  }
530 
531  llvm_unreachable("unknown cast resulting in complex value");
532 }
533 
534 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
535  TestAndClearIgnoreReal();
536  TestAndClearIgnoreImag();
537  ComplexPairTy Op = Visit(E->getSubExpr());
538 
539  llvm::Value *ResR, *ResI;
540  if (Op.first->getType()->isFloatingPointTy()) {
541  ResR = Builder.CreateFNeg(Op.first, "neg.r");
542  ResI = Builder.CreateFNeg(Op.second, "neg.i");
543  } else {
544  ResR = Builder.CreateNeg(Op.first, "neg.r");
545  ResI = Builder.CreateNeg(Op.second, "neg.i");
546  }
547  return ComplexPairTy(ResR, ResI);
548 }
549 
550 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
551  TestAndClearIgnoreReal();
552  TestAndClearIgnoreImag();
553  // ~(a+ib) = a + i*-b
554  ComplexPairTy Op = Visit(E->getSubExpr());
555  llvm::Value *ResI;
556  if (Op.second->getType()->isFloatingPointTy())
557  ResI = Builder.CreateFNeg(Op.second, "conj.i");
558  else
559  ResI = Builder.CreateNeg(Op.second, "conj.i");
560 
561  return ComplexPairTy(Op.first, ResI);
562 }
563 
564 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
565  llvm::Value *ResR, *ResI;
566 
567  if (Op.LHS.first->getType()->isFloatingPointTy()) {
568  ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
569  if (Op.LHS.second && Op.RHS.second)
570  ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
571  else
572  ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
573  assert(ResI && "Only one operand may be real!");
574  } else {
575  ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
576  assert(Op.LHS.second && Op.RHS.second &&
577  "Both operands of integer complex operators must be complex!");
578  ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
579  }
580  return ComplexPairTy(ResR, ResI);
581 }
582 
583 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
584  llvm::Value *ResR, *ResI;
585  if (Op.LHS.first->getType()->isFloatingPointTy()) {
586  ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
587  if (Op.LHS.second && Op.RHS.second)
588  ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
589  else
590  ResI = Op.LHS.second ? Op.LHS.second
591  : Builder.CreateFNeg(Op.RHS.second, "sub.i");
592  assert(ResI && "Only one operand may be real!");
593  } else {
594  ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
595  assert(Op.LHS.second && Op.RHS.second &&
596  "Both operands of integer complex operators must be complex!");
597  ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
598  }
599  return ComplexPairTy(ResR, ResI);
600 }
601 
602 /// Emit a libcall for a binary operation on complex types.
603 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
604  const BinOpInfo &Op) {
605  CallArgList Args;
606  Args.add(RValue::get(Op.LHS.first),
607  Op.Ty->castAs<ComplexType>()->getElementType());
608  Args.add(RValue::get(Op.LHS.second),
609  Op.Ty->castAs<ComplexType>()->getElementType());
610  Args.add(RValue::get(Op.RHS.first),
611  Op.Ty->castAs<ComplexType>()->getElementType());
612  Args.add(RValue::get(Op.RHS.second),
613  Op.Ty->castAs<ComplexType>()->getElementType());
614 
615  // We *must* use the full CG function call building logic here because the
616  // complex type has special ABI handling. We also should not forget about
617  // special calling convention which may be used for compiler builtins.
618 
619  // We create a function qualified type to state that this call does not have
620  // any exceptions.
622  EPI = EPI.withExceptionSpec(
624  SmallVector<QualType, 4> ArgsQTys(
625  4, Op.Ty->castAs<ComplexType>()->getElementType());
626  QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
627  const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
628  Args, cast<FunctionType>(FQTy.getTypePtr()), false);
629 
630  llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
631  llvm::Constant *Func = CGF.CGM.CreateBuiltinFunction(FTy, LibCallName);
632  CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
633 
634  llvm::Instruction *Call;
635  RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
636  cast<llvm::CallInst>(Call)->setCallingConv(CGF.CGM.getRuntimeCC());
637  return Res.getComplexVal();
638 }
639 
640 /// Lookup the libcall name for a given floating point type complex
641 /// multiply.
643  switch (Ty->getTypeID()) {
644  default:
645  llvm_unreachable("Unsupported floating point type!");
646  case llvm::Type::HalfTyID:
647  return "__mulhc3";
648  case llvm::Type::FloatTyID:
649  return "__mulsc3";
650  case llvm::Type::DoubleTyID:
651  return "__muldc3";
652  case llvm::Type::PPC_FP128TyID:
653  return "__multc3";
654  case llvm::Type::X86_FP80TyID:
655  return "__mulxc3";
656  case llvm::Type::FP128TyID:
657  return "__multc3";
658  }
659 }
660 
661 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
662 // typed values.
663 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
664  using llvm::Value;
665  Value *ResR, *ResI;
666  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
667 
668  if (Op.LHS.first->getType()->isFloatingPointTy()) {
669  // The general formulation is:
670  // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
671  //
672  // But we can fold away components which would be zero due to a real
673  // operand according to C11 Annex G.5.1p2.
674  // FIXME: C11 also provides for imaginary types which would allow folding
675  // still more of this within the type system.
676 
677  if (Op.LHS.second && Op.RHS.second) {
678  // If both operands are complex, emit the core math directly, and then
679  // test for NaNs. If we find NaNs in the result, we delegate to a libcall
680  // to carefully re-compute the correct infinity representation if
681  // possible. The expectation is that the presence of NaNs here is
682  // *extremely* rare, and so the cost of the libcall is almost irrelevant.
683  // This is good, because the libcall re-computes the core multiplication
684  // exactly the same as we do here and re-tests for NaNs in order to be
685  // a generic complex*complex libcall.
686 
687  // First compute the four products.
688  Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
689  Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
690  Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
691  Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
692 
693  // The real part is the difference of the first two, the imaginary part is
694  // the sum of the second.
695  ResR = Builder.CreateFSub(AC, BD, "mul_r");
696  ResI = Builder.CreateFAdd(AD, BC, "mul_i");
697 
698  // Emit the test for the real part becoming NaN and create a branch to
699  // handle it. We test for NaN by comparing the number to itself.
700  Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
701  llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
702  llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
703  llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
704  llvm::BasicBlock *OrigBB = Branch->getParent();
705 
706  // Give hint that we very much don't expect to see NaNs.
707  // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
708  llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
709  Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
710 
711  // Now test the imaginary part and create its branch.
712  CGF.EmitBlock(INaNBB);
713  Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
714  llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
715  Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
716  Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
717 
718  // Now emit the libcall on this slowest of the slow paths.
719  CGF.EmitBlock(LibCallBB);
720  Value *LibCallR, *LibCallI;
721  std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
722  getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
723  Builder.CreateBr(ContBB);
724 
725  // Finally continue execution by phi-ing together the different
726  // computation paths.
727  CGF.EmitBlock(ContBB);
728  llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
729  RealPHI->addIncoming(ResR, OrigBB);
730  RealPHI->addIncoming(ResR, INaNBB);
731  RealPHI->addIncoming(LibCallR, LibCallBB);
732  llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
733  ImagPHI->addIncoming(ResI, OrigBB);
734  ImagPHI->addIncoming(ResI, INaNBB);
735  ImagPHI->addIncoming(LibCallI, LibCallBB);
736  return ComplexPairTy(RealPHI, ImagPHI);
737  }
738  assert((Op.LHS.second || Op.RHS.second) &&
739  "At least one operand must be complex!");
740 
741  // If either of the operands is a real rather than a complex, the
742  // imaginary component is ignored when computing the real component of the
743  // result.
744  ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
745 
746  ResI = Op.LHS.second
747  ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
748  : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
749  } else {
750  assert(Op.LHS.second && Op.RHS.second &&
751  "Both operands of integer complex operators must be complex!");
752  Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
753  Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
754  ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
755 
756  Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
757  Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
758  ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
759  }
760  return ComplexPairTy(ResR, ResI);
761 }
762 
763 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
764 // typed values.
765 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
766  llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
767  llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
768 
769  llvm::Value *DSTr, *DSTi;
770  if (LHSr->getType()->isFloatingPointTy()) {
771  // If we have a complex operand on the RHS and FastMath is not allowed, we
772  // delegate to a libcall to handle all of the complexities and minimize
773  // underflow/overflow cases. When FastMath is allowed we construct the
774  // divide inline using the same algorithm as for integer operands.
775  //
776  // FIXME: We would be able to avoid the libcall in many places if we
777  // supported imaginary types in addition to complex types.
778  if (RHSi && !CGF.getLangOpts().FastMath) {
779  BinOpInfo LibCallOp = Op;
780  // If LHS was a real, supply a null imaginary part.
781  if (!LHSi)
782  LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
783 
784  switch (LHSr->getType()->getTypeID()) {
785  default:
786  llvm_unreachable("Unsupported floating point type!");
787  case llvm::Type::HalfTyID:
788  return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
789  case llvm::Type::FloatTyID:
790  return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
791  case llvm::Type::DoubleTyID:
792  return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
793  case llvm::Type::PPC_FP128TyID:
794  return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
795  case llvm::Type::X86_FP80TyID:
796  return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
797  case llvm::Type::FP128TyID:
798  return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
799  }
800  } else if (RHSi) {
801  if (!LHSi)
802  LHSi = llvm::Constant::getNullValue(RHSi->getType());
803 
804  // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
805  llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
806  llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
807  llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
808 
809  llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
810  llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
811  llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
812 
813  llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
814  llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
815  llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
816 
817  DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
818  DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
819  } else {
820  assert(LHSi && "Can have at most one non-complex operand!");
821 
822  DSTr = Builder.CreateFDiv(LHSr, RHSr);
823  DSTi = Builder.CreateFDiv(LHSi, RHSr);
824  }
825  } else {
826  assert(Op.LHS.second && Op.RHS.second &&
827  "Both operands of integer complex operators must be complex!");
828  // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
829  llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
830  llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
831  llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
832 
833  llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
834  llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
835  llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
836 
837  llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
838  llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
839  llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
840 
841  if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
842  DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
843  DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
844  } else {
845  DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
846  DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
847  }
848  }
849 
850  return ComplexPairTy(DSTr, DSTi);
851 }
852 
853 ComplexExprEmitter::BinOpInfo
854 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
855  TestAndClearIgnoreReal();
856  TestAndClearIgnoreImag();
857  BinOpInfo Ops;
858  if (E->getLHS()->getType()->isRealFloatingType())
859  Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
860  else
861  Ops.LHS = Visit(E->getLHS());
862  if (E->getRHS()->getType()->isRealFloatingType())
863  Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
864  else
865  Ops.RHS = Visit(E->getRHS());
866 
867  Ops.Ty = E->getType();
868  return Ops;
869 }
870 
871 
872 LValue ComplexExprEmitter::
873 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
874  ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
875  RValue &Val) {
876  TestAndClearIgnoreReal();
877  TestAndClearIgnoreImag();
878  QualType LHSTy = E->getLHS()->getType();
879  if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
880  LHSTy = AT->getValueType();
881 
882  BinOpInfo OpInfo;
883 
884  // Load the RHS and LHS operands.
885  // __block variables need to have the rhs evaluated first, plus this should
886  // improve codegen a little.
887  OpInfo.Ty = E->getComputationResultType();
888  QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
889 
890  // The RHS should have been converted to the computation type.
891  if (E->getRHS()->getType()->isRealFloatingType()) {
892  assert(
893  CGF.getContext()
894  .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
895  OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
896  } else {
897  assert(CGF.getContext()
898  .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
899  OpInfo.RHS = Visit(E->getRHS());
900  }
901 
902  LValue LHS = CGF.EmitLValue(E->getLHS());
903 
904  // Load from the l-value and convert it.
905  SourceLocation Loc = E->getExprLoc();
906  if (LHSTy->isAnyComplexType()) {
907  ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
908  OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
909  } else {
910  llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
911  // For floating point real operands we can directly pass the scalar form
912  // to the binary operator emission and potentially get more efficient code.
913  if (LHSTy->isRealFloatingType()) {
914  if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
915  LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
916  OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
917  } else {
918  OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
919  }
920  }
921 
922  // Expand the binary operator.
923  ComplexPairTy Result = (this->*Func)(OpInfo);
924 
925  // Truncate the result and store it into the LHS lvalue.
926  if (LHSTy->isAnyComplexType()) {
927  ComplexPairTy ResVal =
928  EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
929  EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
930  Val = RValue::getComplex(ResVal);
931  } else {
932  llvm::Value *ResVal =
933  CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
934  CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
935  Val = RValue::get(ResVal);
936  }
937 
938  return LHS;
939 }
940 
941 // Compound assignments.
942 ComplexPairTy ComplexExprEmitter::
943 EmitCompoundAssign(const CompoundAssignOperator *E,
944  ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
945  RValue Val;
946  LValue LV = EmitCompoundAssignLValue(E, Func, Val);
947 
948  // The result of an assignment in C is the assigned r-value.
949  if (!CGF.getLangOpts().CPlusPlus)
950  return Val.getComplexVal();
951 
952  // If the lvalue is non-volatile, return the computed value of the assignment.
953  if (!LV.isVolatileQualified())
954  return Val.getComplexVal();
955 
956  return EmitLoadOfLValue(LV, E->getExprLoc());
957 }
958 
959 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
960  ComplexPairTy &Val) {
961  assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
962  E->getRHS()->getType()) &&
963  "Invalid assignment");
964  TestAndClearIgnoreReal();
965  TestAndClearIgnoreImag();
966 
967  // Emit the RHS. __block variables need the RHS evaluated first.
968  Val = Visit(E->getRHS());
969 
970  // Compute the address to store into.
971  LValue LHS = CGF.EmitLValue(E->getLHS());
972 
973  // Store the result value into the LHS lvalue.
974  EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
975 
976  return LHS;
977 }
978 
979 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
980  ComplexPairTy Val;
981  LValue LV = EmitBinAssignLValue(E, Val);
982 
983  // The result of an assignment in C is the assigned r-value.
984  if (!CGF.getLangOpts().CPlusPlus)
985  return Val;
986 
987  // If the lvalue is non-volatile, return the computed value of the assignment.
988  if (!LV.isVolatileQualified())
989  return Val;
990 
991  return EmitLoadOfLValue(LV, E->getExprLoc());
992 }
993 
994 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
995  CGF.EmitIgnoredExpr(E->getLHS());
996  return Visit(E->getRHS());
997 }
998 
999 ComplexPairTy ComplexExprEmitter::
1000 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1001  TestAndClearIgnoreReal();
1002  TestAndClearIgnoreImag();
1003  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1004  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1005  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1006 
1007  // Bind the common expression if necessary.
1008  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1009 
1010 
1012  CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1013  CGF.getProfileCount(E));
1014 
1015  eval.begin(CGF);
1016  CGF.EmitBlock(LHSBlock);
1017  CGF.incrementProfileCounter(E);
1018  ComplexPairTy LHS = Visit(E->getTrueExpr());
1019  LHSBlock = Builder.GetInsertBlock();
1020  CGF.EmitBranch(ContBlock);
1021  eval.end(CGF);
1022 
1023  eval.begin(CGF);
1024  CGF.EmitBlock(RHSBlock);
1025  ComplexPairTy RHS = Visit(E->getFalseExpr());
1026  RHSBlock = Builder.GetInsertBlock();
1027  CGF.EmitBlock(ContBlock);
1028  eval.end(CGF);
1029 
1030  // Create a PHI node for the real part.
1031  llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1032  RealPN->addIncoming(LHS.first, LHSBlock);
1033  RealPN->addIncoming(RHS.first, RHSBlock);
1034 
1035  // Create a PHI node for the imaginary part.
1036  llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1037  ImagPN->addIncoming(LHS.second, LHSBlock);
1038  ImagPN->addIncoming(RHS.second, RHSBlock);
1039 
1040  return ComplexPairTy(RealPN, ImagPN);
1041 }
1042 
1043 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1044  return Visit(E->getChosenSubExpr());
1045 }
1046 
1047 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1048  bool Ignore = TestAndClearIgnoreReal();
1049  (void)Ignore;
1050  assert (Ignore == false && "init list ignored");
1051  Ignore = TestAndClearIgnoreImag();
1052  (void)Ignore;
1053  assert (Ignore == false && "init list ignored");
1054 
1055  if (E->getNumInits() == 2) {
1056  llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1057  llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1058  return ComplexPairTy(Real, Imag);
1059  } else if (E->getNumInits() == 1) {
1060  return Visit(E->getInit(0));
1061  }
1062 
1063  // Empty init list initializes to null
1064  assert(E->getNumInits() == 0 && "Unexpected number of inits");
1065  QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1066  llvm::Type* LTy = CGF.ConvertType(Ty);
1067  llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
1068  return ComplexPairTy(zeroConstant, zeroConstant);
1069 }
1070 
1071 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1072  Address ArgValue = Address::invalid();
1073  Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
1074 
1075  if (!ArgPtr.isValid()) {
1076  CGF.ErrorUnsupported(E, "complex va_arg expression");
1077  llvm::Type *EltTy =
1078  CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1079  llvm::Value *U = llvm::UndefValue::get(EltTy);
1080  return ComplexPairTy(U, U);
1081  }
1082 
1083  return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
1084  E->getExprLoc());
1085 }
1086 
1087 //===----------------------------------------------------------------------===//
1088 // Entry Point into this File
1089 //===----------------------------------------------------------------------===//
1090 
1091 /// EmitComplexExpr - Emit the computation of the specified expression of
1092 /// complex type, ignoring the result.
1094  bool IgnoreImag) {
1095  assert(E && getComplexType(E->getType()) &&
1096  "Invalid complex expression to emit");
1097 
1098  return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1099  .Visit(const_cast<Expr *>(E));
1100 }
1101 
1103  bool isInit) {
1104  assert(E && getComplexType(E->getType()) &&
1105  "Invalid complex expression to emit");
1106  ComplexExprEmitter Emitter(*this);
1107  ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
1108  Emitter.EmitStoreOfComplex(Val, dest, isInit);
1109 }
1110 
1111 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
1113  bool isInit) {
1114  ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1115 }
1116 
1117 /// EmitLoadOfComplex - Load a complex number from the specified address.
1119  SourceLocation loc) {
1120  return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1121 }
1122 
1124  assert(E->getOpcode() == BO_Assign);
1125  ComplexPairTy Val; // ignored
1126  return ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1127 }
1128 
1129 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1130  const ComplexExprEmitter::BinOpInfo &);
1131 
1133  switch (Op) {
1134  case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
1135  case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
1136  case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
1137  case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
1138  default:
1139  llvm_unreachable("unexpected complex compound assignment");
1140  }
1141 }
1142 
1145  CompoundFunc Op = getComplexOp(E->getOpcode());
1146  RValue Val;
1147  return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1148 }
1149 
1152  llvm::Value *&Result) {
1153  CompoundFunc Op = getComplexOp(E->getOpcode());
1154  RValue Val;
1155  LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1156  Result = Val.getScalarVal();
1157  return Ret;
1158 }
const Expr * getSubExpr() const
Definition: Expr.h:890
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:361
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition: Expr.h:3979
LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
A (possibly-)qualified type.
Definition: Type.h:642
SourceLocation getExprLoc() const
Definition: Expr.h:3279
CompoundStmt * getSubStmt()
Definition: Expr.h:3778
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4194
Stmt - This represents one statement.
Definition: Stmt.h:66
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
Expr * getBase() const
Definition: Expr.h:2701
static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty)
Lookup the libcall name for a given floating point type complex multiply.
Opcode getOpcode() const
Definition: Expr.h:3283
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1855
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
const Expr * getResultExpr() const
The generic selection&#39;s result expression.
Definition: Expr.h:5047
const Expr * getSubExpr() const
Definition: Expr.h:1540
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1884
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2859
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6716
Extra information about a function prototype.
Definition: Type.h:3762
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3016
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void add(RValue rvalue, QualType type)
Definition: CGCall.h:285
An object to manage conditionally-evaluated expressions.
LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, llvm::Value *&Result)
Address getAddress() const
Definition: CGValue.h:327
QualType getComputationResultType() const
Definition: Expr.h:3491
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
bool isVolatileQualified() const
Definition: CGValue.h:258
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Expr * getSubExpr()
Definition: Expr.h:2997
const AstTypeMatcher< ComplexType > complexType
Matches C99 complex types.
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
bool isGLValue() const
Definition: Expr.h:252
Describes an C or C++ initializer list.
Definition: Expr.h:4146
Address emitAddrOfRealComponent(Address complex, QualType complexType)
BinaryOperatorKind
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3248
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2932
void ForceCleanup(std::initializer_list< llvm::Value **> ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
bool isSimple() const
Definition: CGValue.h:252
ComplexPairTy(ComplexExprEmitter::* CompoundFunc)(const ComplexExprEmitter::BinOpInfo &)
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1072
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:1161
bool isValid() const
Definition: Address.h:36
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3686
CastKind
CastKind - The kind of operation required for a conversion.
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:39
ConstantExpr - An expression that occurs in a constant context.
Definition: Expr.h:904
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4052
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:1832
QualType getElementType() const
Definition: Type.h:2496
This represents one expression.
Definition: Expr.h:106
static Address invalid()
Definition: Address.h:35
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:66
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6779
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:134
unsigned getNumInits() const
Definition: Expr.h:4176
bool isAnyComplexType() const
Definition: Type.h:6363
QualType getType() const
Definition: Expr.h:128
An RAII object to record that we&#39;re evaluating a statement expression.
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1907
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3853
const Expr * getSubExpr() const
Definition: Expr.h:1871
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1528
The l-value was considered opaque, so the alignment was determined from a type.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:945
QualType getCanonicalType() const
Definition: Type.h:6097
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5260
Encodes a location in the source.
Expr * getSubExpr() const
Definition: Expr.h:1937
CastKind getCastKind() const
Definition: Expr.h:2991
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:684
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:183
static const ComplexType * getComplexType(QualType type)
Return the complex type that we are meant to emit.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, and corresponding __opencl_atomic_* for OpenCL 2.0.
Definition: Expr.h:5394
An aligned address.
Definition: Address.h:25
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3066
All available information about a concrete callee.
Definition: CGCall.h:67
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3762
QualType getType() const
Definition: CGValue.h:264
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
Expr * getLHS() const
Definition: Expr.h:3288
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3465
Represents a C11 generic selection.
Definition: Expr.h:4971
CGFunctionInfo - Class to encapsulate the information about a function definition.
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:983
Dataflow Directional Tag Classes.
static CompoundFunc getComplexOp(BinaryOperatorKind Op)
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:93
CodeGenFunction::ComplexPairTy ComplexPairTy
Represents a &#39;co_yield&#39; expression.
Definition: ExprCXX.h:4397
const Expr * getExpr() const
Definition: ExprCXX.h:1105
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1348
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:3776
Complex values, per C99 6.2.5p11.
Definition: Type.h:2483
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
Definition: ASTDumper.cpp:2379
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3501
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
bool isAtomicType() const
Definition: Type.h:6392
Represents a &#39;co_await&#39; expression.
Definition: ExprCXX.h:4314
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:62
Holds information about the various types of exception specification.
Definition: Type.h:3736
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type, returning the result.
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1136
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2616
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3938
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2407
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1042
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
Expr * getRHS() const
Definition: Expr.h:3290
LValue - This represents an lvalue references.
Definition: CGValue.h:167
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:260
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4854