clang  10.0.0svn
CGExprComplex.cpp
Go to the documentation of this file.
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 
30 
31 /// Return the complex type that we are meant to emit.
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);
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);
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) {
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  ComplexPairTy VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
283  return Visit(E->getSemanticForm());
284  }
285 
286  // Compound assignments.
287  ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
288  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
289  }
290  ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
291  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
292  }
293  ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
294  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
295  }
296  ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
297  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
298  }
299 
300  // GCC rejects rem/and/or/xor for integer complex.
301  // Logical and/or always return int, never complex.
302 
303  // No comparisons produce a complex result.
304 
305  LValue EmitBinAssignLValue(const BinaryOperator *E,
306  ComplexPairTy &Val);
307  ComplexPairTy VisitBinAssign (const BinaryOperator *E);
308  ComplexPairTy VisitBinComma (const BinaryOperator *E);
309 
310 
312  VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
313  ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
314 
315  ComplexPairTy VisitInitListExpr(InitListExpr *E);
316 
317  ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
318  return EmitLoadOfLValue(E);
319  }
320 
321  ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
322 
323  ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
324  return CGF.EmitAtomicExpr(E).getComplexVal();
325  }
326 };
327 } // end anonymous namespace.
328 
329 //===----------------------------------------------------------------------===//
330 // Utilities
331 //===----------------------------------------------------------------------===//
332 
335  return Builder.CreateStructGEP(addr, 0, addr.getName() + ".realp");
336 }
337 
340  return Builder.CreateStructGEP(addr, 1, addr.getName() + ".imagp");
341 }
342 
343 /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
344 /// load the real and imaginary pieces, returning them as Real/Imag.
345 ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
346  SourceLocation loc) {
347  assert(lvalue.isSimple() && "non-simple complex l-value?");
348  if (lvalue.getType()->isAtomicType())
349  return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
350 
351  Address SrcPtr = lvalue.getAddress();
352  bool isVolatile = lvalue.isVolatileQualified();
353 
354  llvm::Value *Real = nullptr, *Imag = nullptr;
355 
356  if (!IgnoreReal || isVolatile) {
357  Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
358  Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
359  }
360 
361  if (!IgnoreImag || isVolatile) {
362  Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
363  Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
364  }
365 
366  return ComplexPairTy(Real, Imag);
367 }
368 
369 /// EmitStoreOfComplex - Store the specified real/imag parts into the
370 /// specified value pointer.
371 void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
372  bool isInit) {
373  if (lvalue.getType()->isAtomicType() ||
374  (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
375  return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
376 
377  Address Ptr = lvalue.getAddress();
378  Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
379  Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
380 
381  Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
382  Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
383 }
384 
385 
386 
387 //===----------------------------------------------------------------------===//
388 // Visitor Methods
389 //===----------------------------------------------------------------------===//
390 
391 ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
392  CGF.ErrorUnsupported(E, "complex expression");
393  llvm::Type *EltTy =
394  CGF.ConvertType(getComplexType(E->getType())->getElementType());
395  llvm::Value *U = llvm::UndefValue::get(EltTy);
396  return ComplexPairTy(U, U);
397 }
398 
399 ComplexPairTy ComplexExprEmitter::
400 VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
401  llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
402  return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
403 }
404 
405 
406 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
407  if (E->getCallReturnType(CGF.getContext())->isReferenceType())
408  return EmitLoadOfLValue(E);
409 
410  return CGF.EmitCallExpr(E).getComplexVal();
411 }
412 
413 ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
415  Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
416  assert(RetAlloca.isValid() && "Expected complex return value");
417  return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
418  E->getExprLoc());
419 }
420 
421 /// Emit a cast from complex value Val to DestType.
422 ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
423  QualType SrcType,
424  QualType DestType,
425  SourceLocation Loc) {
426  // Get the src/dest element type.
427  SrcType = SrcType->castAs<ComplexType>()->getElementType();
428  DestType = DestType->castAs<ComplexType>()->getElementType();
429 
430  // C99 6.3.1.6: When a value of complex type is converted to another
431  // complex type, both the real and imaginary parts follow the conversion
432  // rules for the corresponding real types.
433  Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
434  Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
435  return Val;
436 }
437 
438 ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
439  QualType SrcType,
440  QualType DestType,
441  SourceLocation Loc) {
442  // Convert the input element to the element type of the complex.
443  DestType = DestType->castAs<ComplexType>()->getElementType();
444  Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
445 
446  // Return (realval, 0).
447  return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
448 }
449 
450 ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
451  QualType DestTy) {
452  switch (CK) {
453  case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
454 
455  // Atomic to non-atomic casts may be more than a no-op for some platforms and
456  // for some types.
457  case CK_AtomicToNonAtomic:
458  case CK_NonAtomicToAtomic:
459  case CK_NoOp:
460  case CK_LValueToRValue:
461  case CK_UserDefinedConversion:
462  return Visit(Op);
463 
464  case CK_LValueBitCast: {
465  LValue origLV = CGF.EmitLValue(Op);
466  Address V = origLV.getAddress();
467  V = Builder.CreateElementBitCast(V, CGF.ConvertType(DestTy));
468  return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
469  }
470 
471  case CK_LValueToRValueBitCast: {
472  LValue SourceLVal = CGF.EmitLValue(Op);
473  Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(),
474  CGF.ConvertTypeForMem(DestTy));
475  LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
477  return EmitLoadOfLValue(DestLV, Op->getExprLoc());
478  }
479 
480  case CK_BitCast:
481  case CK_BaseToDerived:
482  case CK_DerivedToBase:
483  case CK_UncheckedDerivedToBase:
484  case CK_Dynamic:
485  case CK_ToUnion:
486  case CK_ArrayToPointerDecay:
487  case CK_FunctionToPointerDecay:
488  case CK_NullToPointer:
489  case CK_NullToMemberPointer:
490  case CK_BaseToDerivedMemberPointer:
491  case CK_DerivedToBaseMemberPointer:
492  case CK_MemberPointerToBoolean:
493  case CK_ReinterpretMemberPointer:
494  case CK_ConstructorConversion:
495  case CK_IntegralToPointer:
496  case CK_PointerToIntegral:
497  case CK_PointerToBoolean:
498  case CK_ToVoid:
499  case CK_VectorSplat:
500  case CK_IntegralCast:
501  case CK_BooleanToSignedIntegral:
502  case CK_IntegralToBoolean:
503  case CK_IntegralToFloating:
504  case CK_FloatingToIntegral:
505  case CK_FloatingToBoolean:
506  case CK_FloatingCast:
507  case CK_CPointerToObjCPointerCast:
508  case CK_BlockPointerToObjCPointerCast:
509  case CK_AnyPointerToBlockPointerCast:
510  case CK_ObjCObjectLValueCast:
511  case CK_FloatingComplexToReal:
512  case CK_FloatingComplexToBoolean:
513  case CK_IntegralComplexToReal:
514  case CK_IntegralComplexToBoolean:
515  case CK_ARCProduceObject:
516  case CK_ARCConsumeObject:
517  case CK_ARCReclaimReturnedObject:
518  case CK_ARCExtendBlockObject:
519  case CK_CopyAndAutoreleaseBlockObject:
520  case CK_BuiltinFnToFnPtr:
521  case CK_ZeroToOCLOpaqueType:
522  case CK_AddressSpaceConversion:
523  case CK_IntToOCLSampler:
524  case CK_FixedPointCast:
525  case CK_FixedPointToBoolean:
526  case CK_FixedPointToIntegral:
527  case CK_IntegralToFixedPoint:
528  llvm_unreachable("invalid cast kind for complex value");
529 
530  case CK_FloatingRealToComplex:
531  case CK_IntegralRealToComplex:
532  return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
533  DestTy, Op->getExprLoc());
534 
535  case CK_FloatingComplexCast:
536  case CK_FloatingComplexToIntegralComplex:
537  case CK_IntegralComplexCast:
538  case CK_IntegralComplexToFloatingComplex:
539  return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
540  Op->getExprLoc());
541  }
542 
543  llvm_unreachable("unknown cast resulting in complex value");
544 }
545 
546 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
547  TestAndClearIgnoreReal();
548  TestAndClearIgnoreImag();
549  ComplexPairTy Op = Visit(E->getSubExpr());
550 
551  llvm::Value *ResR, *ResI;
552  if (Op.first->getType()->isFloatingPointTy()) {
553  ResR = Builder.CreateFNeg(Op.first, "neg.r");
554  ResI = Builder.CreateFNeg(Op.second, "neg.i");
555  } else {
556  ResR = Builder.CreateNeg(Op.first, "neg.r");
557  ResI = Builder.CreateNeg(Op.second, "neg.i");
558  }
559  return ComplexPairTy(ResR, ResI);
560 }
561 
562 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
563  TestAndClearIgnoreReal();
564  TestAndClearIgnoreImag();
565  // ~(a+ib) = a + i*-b
566  ComplexPairTy Op = Visit(E->getSubExpr());
567  llvm::Value *ResI;
568  if (Op.second->getType()->isFloatingPointTy())
569  ResI = Builder.CreateFNeg(Op.second, "conj.i");
570  else
571  ResI = Builder.CreateNeg(Op.second, "conj.i");
572 
573  return ComplexPairTy(Op.first, ResI);
574 }
575 
576 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
577  llvm::Value *ResR, *ResI;
578 
579  if (Op.LHS.first->getType()->isFloatingPointTy()) {
580  ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
581  if (Op.LHS.second && Op.RHS.second)
582  ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
583  else
584  ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
585  assert(ResI && "Only one operand may be real!");
586  } else {
587  ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
588  assert(Op.LHS.second && Op.RHS.second &&
589  "Both operands of integer complex operators must be complex!");
590  ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
591  }
592  return ComplexPairTy(ResR, ResI);
593 }
594 
595 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
596  llvm::Value *ResR, *ResI;
597  if (Op.LHS.first->getType()->isFloatingPointTy()) {
598  ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
599  if (Op.LHS.second && Op.RHS.second)
600  ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
601  else
602  ResI = Op.LHS.second ? Op.LHS.second
603  : Builder.CreateFNeg(Op.RHS.second, "sub.i");
604  assert(ResI && "Only one operand may be real!");
605  } else {
606  ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
607  assert(Op.LHS.second && Op.RHS.second &&
608  "Both operands of integer complex operators must be complex!");
609  ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
610  }
611  return ComplexPairTy(ResR, ResI);
612 }
613 
614 /// Emit a libcall for a binary operation on complex types.
615 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
616  const BinOpInfo &Op) {
617  CallArgList Args;
618  Args.add(RValue::get(Op.LHS.first),
619  Op.Ty->castAs<ComplexType>()->getElementType());
620  Args.add(RValue::get(Op.LHS.second),
621  Op.Ty->castAs<ComplexType>()->getElementType());
622  Args.add(RValue::get(Op.RHS.first),
623  Op.Ty->castAs<ComplexType>()->getElementType());
624  Args.add(RValue::get(Op.RHS.second),
625  Op.Ty->castAs<ComplexType>()->getElementType());
626 
627  // We *must* use the full CG function call building logic here because the
628  // complex type has special ABI handling. We also should not forget about
629  // special calling convention which may be used for compiler builtins.
630 
631  // We create a function qualified type to state that this call does not have
632  // any exceptions.
634  EPI = EPI.withExceptionSpec(
636  SmallVector<QualType, 4> ArgsQTys(
637  4, Op.Ty->castAs<ComplexType>()->getElementType());
638  QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
639  const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
640  Args, cast<FunctionType>(FQTy.getTypePtr()), false);
641 
642  llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
643  llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(
644  FTy, LibCallName, llvm::AttributeList(), true);
645  CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
646 
647  llvm::CallBase *Call;
648  RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
649  Call->setCallingConv(CGF.CGM.getRuntimeCC());
650  return Res.getComplexVal();
651 }
652 
653 /// Lookup the libcall name for a given floating point type complex
654 /// multiply.
656  switch (Ty->getTypeID()) {
657  default:
658  llvm_unreachable("Unsupported floating point type!");
659  case llvm::Type::HalfTyID:
660  return "__mulhc3";
661  case llvm::Type::FloatTyID:
662  return "__mulsc3";
663  case llvm::Type::DoubleTyID:
664  return "__muldc3";
665  case llvm::Type::PPC_FP128TyID:
666  return "__multc3";
667  case llvm::Type::X86_FP80TyID:
668  return "__mulxc3";
669  case llvm::Type::FP128TyID:
670  return "__multc3";
671  }
672 }
673 
674 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
675 // typed values.
676 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
677  using llvm::Value;
678  Value *ResR, *ResI;
679  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
680 
681  if (Op.LHS.first->getType()->isFloatingPointTy()) {
682  // The general formulation is:
683  // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
684  //
685  // But we can fold away components which would be zero due to a real
686  // operand according to C11 Annex G.5.1p2.
687  // FIXME: C11 also provides for imaginary types which would allow folding
688  // still more of this within the type system.
689 
690  if (Op.LHS.second && Op.RHS.second) {
691  // If both operands are complex, emit the core math directly, and then
692  // test for NaNs. If we find NaNs in the result, we delegate to a libcall
693  // to carefully re-compute the correct infinity representation if
694  // possible. The expectation is that the presence of NaNs here is
695  // *extremely* rare, and so the cost of the libcall is almost irrelevant.
696  // This is good, because the libcall re-computes the core multiplication
697  // exactly the same as we do here and re-tests for NaNs in order to be
698  // a generic complex*complex libcall.
699 
700  // First compute the four products.
701  Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
702  Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
703  Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
704  Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
705 
706  // The real part is the difference of the first two, the imaginary part is
707  // the sum of the second.
708  ResR = Builder.CreateFSub(AC, BD, "mul_r");
709  ResI = Builder.CreateFAdd(AD, BC, "mul_i");
710 
711  // Emit the test for the real part becoming NaN and create a branch to
712  // handle it. We test for NaN by comparing the number to itself.
713  Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
714  llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
715  llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
716  llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
717  llvm::BasicBlock *OrigBB = Branch->getParent();
718 
719  // Give hint that we very much don't expect to see NaNs.
720  // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
721  llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
722  Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
723 
724  // Now test the imaginary part and create its branch.
725  CGF.EmitBlock(INaNBB);
726  Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
727  llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
728  Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
729  Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
730 
731  // Now emit the libcall on this slowest of the slow paths.
732  CGF.EmitBlock(LibCallBB);
733  Value *LibCallR, *LibCallI;
734  std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
735  getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
736  Builder.CreateBr(ContBB);
737 
738  // Finally continue execution by phi-ing together the different
739  // computation paths.
740  CGF.EmitBlock(ContBB);
741  llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
742  RealPHI->addIncoming(ResR, OrigBB);
743  RealPHI->addIncoming(ResR, INaNBB);
744  RealPHI->addIncoming(LibCallR, LibCallBB);
745  llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
746  ImagPHI->addIncoming(ResI, OrigBB);
747  ImagPHI->addIncoming(ResI, INaNBB);
748  ImagPHI->addIncoming(LibCallI, LibCallBB);
749  return ComplexPairTy(RealPHI, ImagPHI);
750  }
751  assert((Op.LHS.second || Op.RHS.second) &&
752  "At least one operand must be complex!");
753 
754  // If either of the operands is a real rather than a complex, the
755  // imaginary component is ignored when computing the real component of the
756  // result.
757  ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
758 
759  ResI = Op.LHS.second
760  ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
761  : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
762  } else {
763  assert(Op.LHS.second && Op.RHS.second &&
764  "Both operands of integer complex operators must be complex!");
765  Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
766  Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
767  ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
768 
769  Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
770  Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
771  ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
772  }
773  return ComplexPairTy(ResR, ResI);
774 }
775 
776 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
777 // typed values.
778 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
779  llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
780  llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
781 
782  llvm::Value *DSTr, *DSTi;
783  if (LHSr->getType()->isFloatingPointTy()) {
784  // If we have a complex operand on the RHS and FastMath is not allowed, we
785  // delegate to a libcall to handle all of the complexities and minimize
786  // underflow/overflow cases. When FastMath is allowed we construct the
787  // divide inline using the same algorithm as for integer operands.
788  //
789  // FIXME: We would be able to avoid the libcall in many places if we
790  // supported imaginary types in addition to complex types.
791  if (RHSi && !CGF.getLangOpts().FastMath) {
792  BinOpInfo LibCallOp = Op;
793  // If LHS was a real, supply a null imaginary part.
794  if (!LHSi)
795  LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
796 
797  switch (LHSr->getType()->getTypeID()) {
798  default:
799  llvm_unreachable("Unsupported floating point type!");
800  case llvm::Type::HalfTyID:
801  return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
802  case llvm::Type::FloatTyID:
803  return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
804  case llvm::Type::DoubleTyID:
805  return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
806  case llvm::Type::PPC_FP128TyID:
807  return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
808  case llvm::Type::X86_FP80TyID:
809  return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
810  case llvm::Type::FP128TyID:
811  return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
812  }
813  } else if (RHSi) {
814  if (!LHSi)
815  LHSi = llvm::Constant::getNullValue(RHSi->getType());
816 
817  // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
818  llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
819  llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
820  llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
821 
822  llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
823  llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
824  llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
825 
826  llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
827  llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
828  llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
829 
830  DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
831  DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
832  } else {
833  assert(LHSi && "Can have at most one non-complex operand!");
834 
835  DSTr = Builder.CreateFDiv(LHSr, RHSr);
836  DSTi = Builder.CreateFDiv(LHSi, RHSr);
837  }
838  } else {
839  assert(Op.LHS.second && Op.RHS.second &&
840  "Both operands of integer complex operators must be complex!");
841  // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
842  llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
843  llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
844  llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
845 
846  llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
847  llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
848  llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
849 
850  llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
851  llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
852  llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
853 
854  if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
855  DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
856  DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
857  } else {
858  DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
859  DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
860  }
861  }
862 
863  return ComplexPairTy(DSTr, DSTi);
864 }
865 
866 ComplexExprEmitter::BinOpInfo
867 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
868  TestAndClearIgnoreReal();
869  TestAndClearIgnoreImag();
870  BinOpInfo Ops;
871  if (E->getLHS()->getType()->isRealFloatingType())
872  Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
873  else
874  Ops.LHS = Visit(E->getLHS());
875  if (E->getRHS()->getType()->isRealFloatingType())
876  Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
877  else
878  Ops.RHS = Visit(E->getRHS());
879 
880  Ops.Ty = E->getType();
881  return Ops;
882 }
883 
884 
885 LValue ComplexExprEmitter::
886 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
887  ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
888  RValue &Val) {
889  TestAndClearIgnoreReal();
890  TestAndClearIgnoreImag();
891  QualType LHSTy = E->getLHS()->getType();
892  if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
893  LHSTy = AT->getValueType();
894 
895  BinOpInfo OpInfo;
896 
897  // Load the RHS and LHS operands.
898  // __block variables need to have the rhs evaluated first, plus this should
899  // improve codegen a little.
900  OpInfo.Ty = E->getComputationResultType();
901  QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
902 
903  // The RHS should have been converted to the computation type.
904  if (E->getRHS()->getType()->isRealFloatingType()) {
905  assert(
906  CGF.getContext()
907  .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
908  OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
909  } else {
910  assert(CGF.getContext()
911  .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
912  OpInfo.RHS = Visit(E->getRHS());
913  }
914 
915  LValue LHS = CGF.EmitLValue(E->getLHS());
916 
917  // Load from the l-value and convert it.
918  SourceLocation Loc = E->getExprLoc();
919  if (LHSTy->isAnyComplexType()) {
920  ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
921  OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
922  } else {
923  llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
924  // For floating point real operands we can directly pass the scalar form
925  // to the binary operator emission and potentially get more efficient code.
926  if (LHSTy->isRealFloatingType()) {
927  if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
928  LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
929  OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
930  } else {
931  OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
932  }
933  }
934 
935  // Expand the binary operator.
936  ComplexPairTy Result = (this->*Func)(OpInfo);
937 
938  // Truncate the result and store it into the LHS lvalue.
939  if (LHSTy->isAnyComplexType()) {
940  ComplexPairTy ResVal =
941  EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
942  EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
943  Val = RValue::getComplex(ResVal);
944  } else {
945  llvm::Value *ResVal =
946  CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
947  CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
948  Val = RValue::get(ResVal);
949  }
950 
951  return LHS;
952 }
953 
954 // Compound assignments.
955 ComplexPairTy ComplexExprEmitter::
956 EmitCompoundAssign(const CompoundAssignOperator *E,
957  ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
958  RValue Val;
959  LValue LV = EmitCompoundAssignLValue(E, Func, Val);
960 
961  // The result of an assignment in C is the assigned r-value.
962  if (!CGF.getLangOpts().CPlusPlus)
963  return Val.getComplexVal();
964 
965  // If the lvalue is non-volatile, return the computed value of the assignment.
966  if (!LV.isVolatileQualified())
967  return Val.getComplexVal();
968 
969  return EmitLoadOfLValue(LV, E->getExprLoc());
970 }
971 
972 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
973  ComplexPairTy &Val) {
974  assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
975  E->getRHS()->getType()) &&
976  "Invalid assignment");
977  TestAndClearIgnoreReal();
978  TestAndClearIgnoreImag();
979 
980  // Emit the RHS. __block variables need the RHS evaluated first.
981  Val = Visit(E->getRHS());
982 
983  // Compute the address to store into.
984  LValue LHS = CGF.EmitLValue(E->getLHS());
985 
986  // Store the result value into the LHS lvalue.
987  EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
988 
989  return LHS;
990 }
991 
992 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
993  ComplexPairTy Val;
994  LValue LV = EmitBinAssignLValue(E, Val);
995 
996  // The result of an assignment in C is the assigned r-value.
997  if (!CGF.getLangOpts().CPlusPlus)
998  return Val;
999 
1000  // If the lvalue is non-volatile, return the computed value of the assignment.
1001  if (!LV.isVolatileQualified())
1002  return Val;
1003 
1004  return EmitLoadOfLValue(LV, E->getExprLoc());
1005 }
1006 
1007 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
1008  CGF.EmitIgnoredExpr(E->getLHS());
1009  return Visit(E->getRHS());
1010 }
1011 
1012 ComplexPairTy ComplexExprEmitter::
1013 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1014  TestAndClearIgnoreReal();
1015  TestAndClearIgnoreImag();
1016  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1017  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1018  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1019 
1020  // Bind the common expression if necessary.
1021  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1022 
1023 
1025  CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1026  CGF.getProfileCount(E));
1027 
1028  eval.begin(CGF);
1029  CGF.EmitBlock(LHSBlock);
1030  CGF.incrementProfileCounter(E);
1031  ComplexPairTy LHS = Visit(E->getTrueExpr());
1032  LHSBlock = Builder.GetInsertBlock();
1033  CGF.EmitBranch(ContBlock);
1034  eval.end(CGF);
1035 
1036  eval.begin(CGF);
1037  CGF.EmitBlock(RHSBlock);
1038  ComplexPairTy RHS = Visit(E->getFalseExpr());
1039  RHSBlock = Builder.GetInsertBlock();
1040  CGF.EmitBlock(ContBlock);
1041  eval.end(CGF);
1042 
1043  // Create a PHI node for the real part.
1044  llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1045  RealPN->addIncoming(LHS.first, LHSBlock);
1046  RealPN->addIncoming(RHS.first, RHSBlock);
1047 
1048  // Create a PHI node for the imaginary part.
1049  llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1050  ImagPN->addIncoming(LHS.second, LHSBlock);
1051  ImagPN->addIncoming(RHS.second, RHSBlock);
1052 
1053  return ComplexPairTy(RealPN, ImagPN);
1054 }
1055 
1056 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1057  return Visit(E->getChosenSubExpr());
1058 }
1059 
1060 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1061  bool Ignore = TestAndClearIgnoreReal();
1062  (void)Ignore;
1063  assert (Ignore == false && "init list ignored");
1064  Ignore = TestAndClearIgnoreImag();
1065  (void)Ignore;
1066  assert (Ignore == false && "init list ignored");
1067 
1068  if (E->getNumInits() == 2) {
1069  llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1070  llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1071  return ComplexPairTy(Real, Imag);
1072  } else if (E->getNumInits() == 1) {
1073  return Visit(E->getInit(0));
1074  }
1075 
1076  // Empty init list initializes to null
1077  assert(E->getNumInits() == 0 && "Unexpected number of inits");
1078  QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1079  llvm::Type* LTy = CGF.ConvertType(Ty);
1080  llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
1081  return ComplexPairTy(zeroConstant, zeroConstant);
1082 }
1083 
1084 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1085  Address ArgValue = Address::invalid();
1086  Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
1087 
1088  if (!ArgPtr.isValid()) {
1089  CGF.ErrorUnsupported(E, "complex va_arg expression");
1090  llvm::Type *EltTy =
1091  CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1092  llvm::Value *U = llvm::UndefValue::get(EltTy);
1093  return ComplexPairTy(U, U);
1094  }
1095 
1096  return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
1097  E->getExprLoc());
1098 }
1099 
1100 //===----------------------------------------------------------------------===//
1101 // Entry Point into this File
1102 //===----------------------------------------------------------------------===//
1103 
1104 /// EmitComplexExpr - Emit the computation of the specified expression of
1105 /// complex type, ignoring the result.
1107  bool IgnoreImag) {
1108  assert(E && getComplexType(E->getType()) &&
1109  "Invalid complex expression to emit");
1110 
1111  return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1112  .Visit(const_cast<Expr *>(E));
1113 }
1114 
1116  bool isInit) {
1117  assert(E && getComplexType(E->getType()) &&
1118  "Invalid complex expression to emit");
1119  ComplexExprEmitter Emitter(*this);
1120  ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
1121  Emitter.EmitStoreOfComplex(Val, dest, isInit);
1122 }
1123 
1124 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
1126  bool isInit) {
1127  ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1128 }
1129 
1130 /// EmitLoadOfComplex - Load a complex number from the specified address.
1132  SourceLocation loc) {
1133  return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1134 }
1135 
1137  assert(E->getOpcode() == BO_Assign);
1138  ComplexPairTy Val; // ignored
1139  return ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1140 }
1141 
1142 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1143  const ComplexExprEmitter::BinOpInfo &);
1144 
1146  switch (Op) {
1147  case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
1148  case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
1149  case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
1150  case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
1151  default:
1152  llvm_unreachable("unexpected complex compound assignment");
1153  }
1154 }
1155 
1158  CompoundFunc Op = getComplexOp(E->getOpcode());
1159  RValue Val;
1160  return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1161 }
1162 
1165  llvm::Value *&Result) {
1166  CompoundFunc Op = getComplexOp(E->getOpcode());
1167  RValue Val;
1168  LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1169  Result = Val.getScalarVal();
1170  return Ret;
1171 }
const Expr * getSubExpr() const
Definition: Expr.h:938
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:363
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:4143
LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
A (possibly-)qualified type.
Definition: Type.h:643
SourceLocation getExprLoc() const
Definition: Expr.h:3440
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition: Expr.h:5398
CompoundStmt * getSubStmt()
Definition: Expr.h:3942
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4423
Stmt - This represents one statement.
Definition: Stmt.h:66
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2024
Expr * getBase() const
Definition: Expr.h:2888
static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty)
Lookup the libcall name for a given floating point type complex multiply.
Opcode getOpcode() const
Definition: Expr.h:3444
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1969
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 * getSubExpr() const
Definition: Expr.h:1649
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:1971
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3052
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6858
Extra information about a function prototype.
Definition: Type.h:3805
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:3306
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void add(RValue rvalue, QualType type)
Definition: CGCall.h:287
An object to manage conditionally-evaluated expressions.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition: ExprCXX.h:293
LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, llvm::Value *&Result)
Address getAddress() const
Definition: CGValue.h:326
QualType getComputationResultType() const
Definition: Expr.h:3655
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
bool isVolatileQualified() const
Definition: CGValue.h:257
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Expr * getSubExpr()
Definition: Expr.h:3177
const AstTypeMatcher< ComplexType > complexType
Matches C99 complex types.
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:255
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
bool isGLValue() const
Definition: Expr.h:261
Describes an C or C++ initializer list.
Definition: Expr.h:4375
Address emitAddrOfRealComponent(Address complex, QualType complexType)
BinaryOperatorKind
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3409
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:3125
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:251
ComplexPairTy(ComplexExprEmitter::* CompoundFunc)(const ComplexExprEmitter::BinOpInfo &)
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1202
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:1307
bool isValid() const
Definition: Address.h:35
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3725
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:38
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:953
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4216
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:2053
QualType getElementType() const
Definition: Type.h:2538
This represents one expression.
Definition: Expr.h:108
static Address invalid()
Definition: Address.h:34
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:65
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6923
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:133
#define V(N, I)
Definition: ASTContext.h:2921
unsigned getNumInits() const
Definition: Expr.h:4405
bool isAnyComplexType() const
Definition: Type.h:6479
QualType getType() const
Definition: Expr.h:137
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:950
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:2021
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4209
const Expr * getSubExpr() const
Definition: Expr.h:1985
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1637
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:1050
QualType getCanonicalType() const
Definition: Type.h:6187
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5673
Encodes a location in the source.
Expr * getSubExpr() const
Definition: Expr.h:2051
static bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.cpp:34
CastKind getCastKind() const
Definition: Expr.h:3171
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:711
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:182
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:5807
An aligned address.
Definition: Address.h:24
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3249
All available information about a concrete callee.
Definition: CGCall.h:66
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3926
QualType getType() const
Definition: CGValue.h:263
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:221
Expr * getLHS() const
Definition: Expr.h:3449
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3629
Represents a C11 generic selection.
Definition: Expr.h:5206
CGFunctionInfo - Class to encapsulate the information about a function definition.
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:1088
Dataflow Directional Tag Classes.
static CompoundFunc getComplexOp(BinaryOperatorKind Op)
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:92
CodeGenFunction::ComplexPairTy ComplexPairTy
Represents a &#39;co_yield&#39; expression.
Definition: ExprCXX.h:4792
const Expr * getExpr() const
Definition: ExprCXX.h:1241
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1496
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:3819
Complex values, per C99 6.2.5p11.
Definition: Type.h:2525
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
Definition: ASTDumper.cpp:243
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3665
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
bool isAtomicType() const
Definition: Type.h:6508
Represents a &#39;co_await&#39; expression.
Definition: ExprCXX.h:4705
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:61
Holds information about the various types of exception specification.
Definition: Type.h:3779
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:546
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1279
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2811
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4102
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2521
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:273
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1146
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
Expr * getRHS() const
Definition: Expr.h:3451
bool Null(InterpState &S, CodePtr OpPC)
Definition: Interp.h:821
LValue - This represents an lvalue references.
Definition: CGValue.h:166
void setTBAAInfo(TBAAAccessInfo Info)
Definition: CGValue.h:308
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:262
static TBAAAccessInfo getMayAliasInfo()
Definition: CodeGenTBAA.h:63
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5089