clang 23.0.0git
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 "CGDebugInfo.h"
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "ConstantEmitter.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/MDBuilder.h"
22#include "llvm/IR/Metadata.h"
23using namespace clang;
24using 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
42namespace {
43class ComplexExprEmitter
44 : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
45 CodeGenFunction &CGF;
46 CGBuilderTy &Builder;
47 bool IgnoreReal;
48 bool IgnoreImag;
49 bool FPHasBeenPromoted;
50
51public:
52 ComplexExprEmitter(CodeGenFunction &cgf, bool ir = false, bool ii = false)
53 : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii),
54 FPHasBeenPromoted(false) {}
55
56 //===--------------------------------------------------------------------===//
57 // Utilities
58 //===--------------------------------------------------------------------===//
59
60 bool TestAndClearIgnoreReal() {
61 bool I = IgnoreReal;
62 IgnoreReal = false;
63 return I;
64 }
65 bool TestAndClearIgnoreImag() {
66 bool I = IgnoreImag;
67 IgnoreImag = false;
68 return I;
69 }
70
71 /// EmitLoadOfLValue - Given an expression with complex type that represents a
72 /// value l-value, this method emits the address of the l-value, then loads
73 /// and returns the result.
74 ComplexPairTy EmitLoadOfLValue(const Expr *E) {
75 return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
76 }
77
78 ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
79
80 /// EmitStoreOfComplex - Store the specified real/imag parts into the
81 /// specified value pointer.
82 void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
83
84 /// Emit a cast from complex value Val to DestType.
85 ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
86 QualType DestType, SourceLocation Loc);
87 /// Emit a cast from scalar value Val to DestType.
88 ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
89 QualType DestType, SourceLocation Loc);
90
91 //===--------------------------------------------------------------------===//
92 // Visitor Methods
93 //===--------------------------------------------------------------------===//
94
95 ComplexPairTy Visit(Expr *E) {
96 ApplyDebugLocation DL(CGF, E);
97 return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
98 }
99
100 ComplexPairTy VisitStmt(Stmt *S) {
101 S->dump(llvm::errs(), CGF.getContext());
102 llvm_unreachable("Stmt can't have complex result type!");
103 }
104 ComplexPairTy VisitExpr(Expr *S);
105 ComplexPairTy VisitConstantExpr(ConstantExpr *E) {
106 if (llvm::Constant *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E))
107 return ComplexPairTy(Result->getAggregateElement(0U),
108 Result->getAggregateElement(1U));
109 return Visit(E->getSubExpr());
110 }
111 ComplexPairTy VisitParenExpr(ParenExpr *PE) {
112 return Visit(PE->getSubExpr());
113 }
114 ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
115 return Visit(GE->getResultExpr());
116 }
117 ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
119 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
120 return Visit(PE->getReplacement());
121 }
122 ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {
123 return CGF.EmitCoawaitExpr(*S).getComplexVal();
124 }
125 ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {
126 return CGF.EmitCoyieldExpr(*S).getComplexVal();
127 }
128 ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {
129 return Visit(E->getSubExpr());
130 }
131
132 ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,
133 Expr *E) {
134 assert(Constant && "not a constant");
135 if (Constant.isReference())
136 return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),
137 E->getExprLoc());
138
139 llvm::Constant *pair = Constant.getValue();
140 return ComplexPairTy(pair->getAggregateElement(0U),
141 pair->getAggregateElement(1U));
142 }
143
144 // l-values.
145 ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
146 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
147 return emitConstant(Constant, E);
148 return EmitLoadOfLValue(E);
149 }
150 ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
151 return EmitLoadOfLValue(E);
152 }
153 ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
154 return CGF.EmitObjCMessageExpr(E).getComplexVal();
155 }
156 ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
157 ComplexPairTy VisitMemberExpr(MemberExpr *ME) {
158 if (CodeGenFunction::ConstantEmission Constant =
159 CGF.tryEmitAsConstant(ME)) {
160 CGF.EmitIgnoredExpr(ME->getBase());
161 return emitConstant(Constant, ME);
162 }
163 return EmitLoadOfLValue(ME);
164 }
165 ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
166 if (E->isGLValue())
167 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
168 E->getExprLoc());
170 }
171
172 ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
174 }
175
176 // FIXME: CompoundLiteralExpr
177
178 ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
179 ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
180 // Unlike for scalars, we don't have to worry about function->ptr demotion
181 // here.
183 return EmitLoadOfLValue(E);
184 return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
185 }
186 ComplexPairTy VisitCastExpr(CastExpr *E) {
187 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
188 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
190 return EmitLoadOfLValue(E);
191 return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
192 }
193 ComplexPairTy VisitCallExpr(const CallExpr *E);
194 ComplexPairTy VisitStmtExpr(const StmtExpr *E);
195
196 // Operators.
197 ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E, bool isInc,
198 bool isPre) {
199 LValue LV = CGF.EmitLValue(E->getSubExpr());
200 return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
201 }
202 ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
203 return VisitPrePostIncDec(E, false, false);
204 }
205 ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
206 return VisitPrePostIncDec(E, true, false);
207 }
208 ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
209 return VisitPrePostIncDec(E, false, true);
210 }
211 ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
212 return VisitPrePostIncDec(E, true, true);
213 }
214 ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
215
216 ComplexPairTy VisitUnaryPlus(const UnaryOperator *E,
217 QualType PromotionType = QualType());
218 ComplexPairTy VisitPlus(const UnaryOperator *E, QualType PromotionType);
219 ComplexPairTy VisitUnaryMinus(const UnaryOperator *E,
220 QualType PromotionType = QualType());
221 ComplexPairTy VisitMinus(const UnaryOperator *E, QualType PromotionType);
222 ComplexPairTy VisitUnaryNot(const UnaryOperator *E);
223 // LNot,Real,Imag never return complex.
224 ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
225 return Visit(E->getSubExpr());
226 }
227 ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
228 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
229 return Visit(DAE->getExpr());
230 }
231 ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
232 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
233 return Visit(DIE->getExpr());
234 }
235 ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
236 CodeGenFunction::RunCleanupsScope Scope(CGF);
237 ComplexPairTy Vals = Visit(E->getSubExpr());
238 // Defend against dominance problems caused by jumps out of expression
239 // evaluation through the shared cleanup block.
240 Scope.ForceCleanup({&Vals.first, &Vals.second});
241 return Vals;
242 }
243 ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
244 assert(E->getType()->isAnyComplexType() && "Expected complex type!");
245 QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
246 llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
247 return ComplexPairTy(Null, Null);
248 }
249 ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
250 assert(E->getType()->isAnyComplexType() && "Expected complex type!");
251 QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
252 llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
253 return ComplexPairTy(Null, Null);
254 }
255
256 struct BinOpInfo {
257 ComplexPairTy LHS;
258 ComplexPairTy RHS;
259 QualType Ty; // Computation Type.
260 FPOptions FPFeatures;
261 };
262
263 BinOpInfo EmitBinOps(const BinaryOperator *E,
264 QualType PromotionTy = QualType());
265 ComplexPairTy EmitPromoted(const Expr *E, QualType PromotionTy);
266 ComplexPairTy EmitPromotedComplexOperand(const Expr *E, QualType PromotionTy);
267 LValue EmitCompoundAssignLValue(
268 const CompoundAssignOperator *E,
269 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo &),
270 RValue &Val);
271 ComplexPairTy EmitCompoundAssign(
272 const CompoundAssignOperator *E,
273 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo &));
274
275 ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
276 ComplexPairTy EmitBinSub(const BinOpInfo &Op);
277 ComplexPairTy EmitBinMul(const BinOpInfo &Op);
278 ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
279 ComplexPairTy EmitAlgebraicDiv(llvm::Value *A, llvm::Value *B, llvm::Value *C,
280 llvm::Value *D);
281 ComplexPairTy EmitRangeReductionDiv(llvm::Value *A, llvm::Value *B,
282 llvm::Value *C, llvm::Value *D);
283
284 ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
285 const BinOpInfo &Op);
286
287 QualType HigherPrecisionTypeForComplexArithmetic(QualType ElementType) {
288 ASTContext &Ctx = CGF.getContext();
289 const QualType HigherElementType =
290 Ctx.GetHigherPrecisionFPType(ElementType);
291 const llvm::fltSemantics &ElementTypeSemantics =
292 Ctx.getFloatTypeSemantics(ElementType);
293 const llvm::fltSemantics &HigherElementTypeSemantics =
294 Ctx.getFloatTypeSemantics(HigherElementType);
295 // Check that the promoted type can handle the intermediate values without
296 // overflowing. This can be interpreted as:
297 // (SmallerType.LargestFiniteVal * SmallerType.LargestFiniteVal) * 2 <=
298 // LargerType.LargestFiniteVal.
299 // In terms of exponent it gives this formula:
300 // (SmallerType.LargestFiniteVal * SmallerType.LargestFiniteVal
301 // doubles the exponent of SmallerType.LargestFiniteVal)
302 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 <=
303 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
304 if (!Ctx.getTargetInfo().hasLongDoubleType() &&
305 HigherElementType.getCanonicalType().getUnqualifiedType() ==
306 Ctx.LongDoubleTy)
307 return QualType();
308 FPHasBeenPromoted = true;
309 return Ctx.getComplexType(HigherElementType);
310 } else {
311 // The intermediate values can't be represented in the promoted type
312 // without overflowing.
313 return QualType();
314 }
315 }
316
317 QualType getPromotionType(FPOptionsOverride Features, QualType Ty,
318 bool IsComplexDivisor) {
319 if (auto *CT = Ty->getAs<ComplexType>()) {
320 QualType ElementType = CT->getElementType().getCanonicalType();
321 bool IsFloatingType = ElementType->isFloatingType();
322 bool IsComplexRangePromoted = CGF.getLangOpts().getComplexRange() ==
323 LangOptions::ComplexRangeKind::CX_Promoted;
324 bool HasNoComplexRangeOverride = !Features.hasComplexRangeOverride();
325 bool HasMatchingComplexRange = Features.hasComplexRangeOverride() &&
326 Features.getComplexRangeOverride() ==
327 CGF.getLangOpts().getComplexRange();
328
329 if (IsComplexDivisor && IsFloatingType && IsComplexRangePromoted &&
330 (HasNoComplexRangeOverride || HasMatchingComplexRange))
331 return HigherPrecisionTypeForComplexArithmetic(ElementType);
332 if (ElementType.UseExcessPrecision(CGF.getContext()))
333 return CGF.getContext().getComplexType(CGF.getContext().FloatTy);
334 }
335 if (Ty.UseExcessPrecision(CGF.getContext()))
336 return CGF.getContext().FloatTy;
337 return QualType();
338 }
339
340#define HANDLEBINOP(OP) \
341 ComplexPairTy VisitBin##OP(const BinaryOperator *E) { \
342 QualType promotionTy = \
343 getPromotionType(E->getStoredFPFeaturesOrDefault(), E->getType(), \
344 (E->getOpcode() == BinaryOperatorKind::BO_Div && \
345 E->getRHS()->getType()->isAnyComplexType())); \
346 ComplexPairTy result = EmitBin##OP(EmitBinOps(E, promotionTy)); \
347 if (!promotionTy.isNull()) \
348 result = CGF.EmitUnPromotedValue(result, E->getType()); \
349 return result; \
350 }
351
352 HANDLEBINOP(Mul)
353 HANDLEBINOP(Div)
354 HANDLEBINOP(Add)
355 HANDLEBINOP(Sub)
356#undef HANDLEBINOP
357
358 ComplexPairTy VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
359 return Visit(E->getSemanticForm());
360 }
361
362 // Compound assignments.
363 ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
364 ApplyAtomGroup Grp(CGF.getDebugInfo());
365 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
366 }
367 ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
368 ApplyAtomGroup Grp(CGF.getDebugInfo());
369 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
370 }
371 ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
372 ApplyAtomGroup Grp(CGF.getDebugInfo());
373 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
374 }
375 ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
376 ApplyAtomGroup Grp(CGF.getDebugInfo());
377 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
378 }
379
380 // GCC rejects rem/and/or/xor for integer complex.
381 // Logical and/or always return int, never complex.
382
383 // No comparisons produce a complex result.
384
385 LValue EmitBinAssignLValue(const BinaryOperator *E, ComplexPairTy &Val);
386 ComplexPairTy VisitBinAssign(const BinaryOperator *E);
387 ComplexPairTy VisitBinComma(const BinaryOperator *E);
388
390 VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
391 ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
392
393 ComplexPairTy VisitInitListExpr(InitListExpr *E);
394
395 ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
396 return EmitLoadOfLValue(E);
397 }
398
399 ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
400
401 ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
402 return CGF.EmitAtomicExpr(E).getComplexVal();
403 }
404
405 ComplexPairTy VisitPackIndexingExpr(PackIndexingExpr *E) {
406 return Visit(E->getSelectedExpr());
407 }
408};
409} // end anonymous namespace.
410
411//===----------------------------------------------------------------------===//
412// Utilities
413//===----------------------------------------------------------------------===//
414
417 return Builder.CreateStructGEP(addr, 0, addr.getName() + ".realp");
418}
419
422 return Builder.CreateStructGEP(addr, 1, addr.getName() + ".imagp");
423}
424
425/// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
426/// load the real and imaginary pieces, returning them as Real/Imag.
427ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
428 SourceLocation loc) {
429 assert(lvalue.isSimple() && "non-simple complex l-value?");
430 if (lvalue.getType()->isAtomicType())
431 return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
432
433 Address SrcPtr = lvalue.getAddress();
434 bool isVolatile = lvalue.isVolatileQualified();
435
436 llvm::Value *Real = nullptr, *Imag = nullptr;
437
438 if (!IgnoreReal || isVolatile) {
439 Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
440 Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
441 }
442
443 if (!IgnoreImag || isVolatile) {
444 Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
445 Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
446 }
447
448 return ComplexPairTy(Real, Imag);
449}
450
451/// EmitStoreOfComplex - Store the specified real/imag parts into the
452/// specified value pointer.
453void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
454 bool isInit) {
455 if (lvalue.getType()->isAtomicType() ||
456 (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
457 return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
458
459 Address Ptr = lvalue.getAddress();
460 Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
461 Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
462
463 auto *R =
464 Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
465 CGF.addInstToCurrentSourceAtom(R, Val.first);
466 auto *I =
467 Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
468 CGF.addInstToCurrentSourceAtom(I, Val.second);
469}
470
471//===----------------------------------------------------------------------===//
472// Visitor Methods
473//===----------------------------------------------------------------------===//
474
475ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
476 CGF.ErrorUnsupported(E, "complex expression");
477 llvm::Type *EltTy =
479 llvm::Value *U = llvm::PoisonValue::get(EltTy);
480 return ComplexPairTy(U, U);
481}
482
484ComplexExprEmitter::VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
485 llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
486 return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
487}
488
489ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
491 return EmitLoadOfLValue(E);
492
493 return CGF.EmitCallExpr(E).getComplexVal();
494}
495
496ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
498 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
499 assert(RetAlloca.isValid() && "Expected complex return value");
500 return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
501 E->getExprLoc());
502}
503
504/// Emit a cast from complex value Val to DestType.
505ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
506 QualType SrcType,
507 QualType DestType,
508 SourceLocation Loc) {
509 // Get the src/dest element type.
510 SrcType = SrcType.getAtomicUnqualifiedType()
511 ->castAs<ComplexType>()
512 ->getElementType();
513 DestType = DestType.getAtomicUnqualifiedType()
514 ->castAs<ComplexType>()
515 ->getElementType();
516
517 // C99 6.3.1.6: When a value of complex type is converted to another
518 // complex type, both the real and imaginary parts follow the conversion
519 // rules for the corresponding real types.
520 if (Val.first)
521 Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
522 if (Val.second)
523 Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
524 return Val;
525}
526
527ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
528 QualType SrcType,
529 QualType DestType,
530 SourceLocation Loc) {
531 // Convert the input element to the element type of the complex.
532 DestType = DestType->castAs<ComplexType>()->getElementType();
533 Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
534
535 // Return (realval, 0).
536 return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
537}
538
539ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
540 QualType DestTy) {
541 DestTy = DestTy.getAtomicUnqualifiedType();
542 switch (CK) {
543 case CK_Dependent:
544 llvm_unreachable("dependent cast kind in IR gen!");
545
546 // Atomic to non-atomic casts may be more than a no-op for some platforms and
547 // for some types.
548 case CK_AtomicToNonAtomic:
549 case CK_NonAtomicToAtomic:
550 case CK_NoOp:
551 case CK_LValueToRValue:
552 case CK_UserDefinedConversion:
553 return Visit(Op);
554
555 case CK_LValueBitCast: {
556 LValue origLV = CGF.EmitLValue(Op);
557 Address V = origLV.getAddress().withElementType(CGF.ConvertType(DestTy));
558 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
559 }
560
561 case CK_LValueToRValueBitCast: {
562 LValue SourceLVal = CGF.EmitLValue(Op);
563 Address Addr =
564 SourceLVal.getAddress().withElementType(CGF.ConvertTypeForMem(DestTy));
565 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
566 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
567 return EmitLoadOfLValue(DestLV, Op->getExprLoc());
568 }
569
570 case CK_BitCast:
571 case CK_BaseToDerived:
572 case CK_DerivedToBase:
573 case CK_UncheckedDerivedToBase:
574 case CK_Dynamic:
575 case CK_ToUnion:
576 case CK_ArrayToPointerDecay:
577 case CK_FunctionToPointerDecay:
578 case CK_NullToPointer:
579 case CK_NullToMemberPointer:
580 case CK_BaseToDerivedMemberPointer:
581 case CK_DerivedToBaseMemberPointer:
582 case CK_MemberPointerToBoolean:
583 case CK_ReinterpretMemberPointer:
584 case CK_ConstructorConversion:
585 case CK_IntegralToPointer:
586 case CK_PointerToIntegral:
587 case CK_PointerToBoolean:
588 case CK_ToVoid:
589 case CK_VectorSplat:
590 case CK_IntegralCast:
591 case CK_BooleanToSignedIntegral:
592 case CK_IntegralToBoolean:
593 case CK_IntegralToFloating:
594 case CK_FloatingToIntegral:
595 case CK_FloatingToBoolean:
596 case CK_FloatingCast:
597 case CK_CPointerToObjCPointerCast:
598 case CK_BlockPointerToObjCPointerCast:
599 case CK_AnyPointerToBlockPointerCast:
600 case CK_ObjCObjectLValueCast:
601 case CK_FloatingComplexToReal:
602 case CK_FloatingComplexToBoolean:
603 case CK_IntegralComplexToReal:
604 case CK_IntegralComplexToBoolean:
605 case CK_ARCProduceObject:
606 case CK_ARCConsumeObject:
607 case CK_ARCReclaimReturnedObject:
608 case CK_ARCExtendBlockObject:
609 case CK_CopyAndAutoreleaseBlockObject:
610 case CK_BuiltinFnToFnPtr:
611 case CK_ZeroToOCLOpaqueType:
612 case CK_AddressSpaceConversion:
613 case CK_IntToOCLSampler:
614 case CK_FloatingToFixedPoint:
615 case CK_FixedPointToFloating:
616 case CK_FixedPointCast:
617 case CK_FixedPointToBoolean:
618 case CK_FixedPointToIntegral:
619 case CK_IntegralToFixedPoint:
620 case CK_MatrixCast:
621 case CK_HLSLVectorTruncation:
622 case CK_HLSLMatrixTruncation:
623 case CK_HLSLArrayRValue:
624 case CK_HLSLElementwiseCast:
625 case CK_HLSLAggregateSplatCast:
626 llvm_unreachable("invalid cast kind for complex value");
627
628 case CK_FloatingRealToComplex:
629 case CK_IntegralRealToComplex: {
630 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
631 return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
632 DestTy, Op->getExprLoc());
633 }
634
635 case CK_FloatingComplexCast:
636 case CK_FloatingComplexToIntegralComplex:
637 case CK_IntegralComplexCast:
638 case CK_IntegralComplexToFloatingComplex: {
639 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
640 return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
641 Op->getExprLoc());
642 }
643 }
644
645 llvm_unreachable("unknown cast resulting in complex value");
646}
647
648ComplexPairTy ComplexExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
649 QualType PromotionType) {
650 QualType promotionTy =
651 PromotionType.isNull()
652 ? getPromotionType(E->getStoredFPFeaturesOrDefault(),
653 E->getSubExpr()->getType(),
654 /*IsComplexDivisor=*/false)
655 : PromotionType;
656 ComplexPairTy result = VisitPlus(E, promotionTy);
657 if (!promotionTy.isNull())
658 return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());
659 return result;
660}
661
662ComplexPairTy ComplexExprEmitter::VisitPlus(const UnaryOperator *E,
663 QualType PromotionType) {
664 TestAndClearIgnoreReal();
665 TestAndClearIgnoreImag();
666 if (!PromotionType.isNull())
667 return CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);
668 return Visit(E->getSubExpr());
669}
670
671ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
672 QualType PromotionType) {
673 QualType promotionTy =
674 PromotionType.isNull()
675 ? getPromotionType(E->getStoredFPFeaturesOrDefault(),
676 E->getSubExpr()->getType(),
677 /*IsComplexDivisor=*/false)
678 : PromotionType;
679 ComplexPairTy result = VisitMinus(E, promotionTy);
680 if (!promotionTy.isNull())
681 return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());
682 return result;
683}
684ComplexPairTy ComplexExprEmitter::VisitMinus(const UnaryOperator *E,
685 QualType PromotionType) {
686 TestAndClearIgnoreReal();
687 TestAndClearIgnoreImag();
688 ComplexPairTy Op;
689 if (!PromotionType.isNull())
690 Op = CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);
691 else
692 Op = Visit(E->getSubExpr());
693
694 llvm::Value *ResR, *ResI;
695 if (Op.first->getType()->isFloatingPointTy()) {
696 ResR = Builder.CreateFNeg(Op.first, "neg.r");
697 ResI = Builder.CreateFNeg(Op.second, "neg.i");
698 } else {
699 ResR = Builder.CreateNeg(Op.first, "neg.r");
700 ResI = Builder.CreateNeg(Op.second, "neg.i");
701 }
702 return ComplexPairTy(ResR, ResI);
703}
704
705ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
706 TestAndClearIgnoreReal();
707 TestAndClearIgnoreImag();
708 // ~(a+ib) = a + i*-b
709 ComplexPairTy Op = Visit(E->getSubExpr());
710 llvm::Value *ResI;
711 if (Op.second->getType()->isFloatingPointTy())
712 ResI = Builder.CreateFNeg(Op.second, "conj.i");
713 else
714 ResI = Builder.CreateNeg(Op.second, "conj.i");
715
716 return ComplexPairTy(Op.first, ResI);
717}
718
719ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
720 llvm::Value *ResR, *ResI;
721
722 if (Op.LHS.first->getType()->isFloatingPointTy()) {
723 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
724 ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
725 if (Op.LHS.second && Op.RHS.second)
726 ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
727 else
728 ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
729 assert(ResI && "Only one operand may be real!");
730 } else {
731 ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
732 assert(Op.LHS.second && Op.RHS.second &&
733 "Both operands of integer complex operators must be complex!");
734 ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
735 }
736 return ComplexPairTy(ResR, ResI);
737}
738
739ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
740 llvm::Value *ResR, *ResI;
741 if (Op.LHS.first->getType()->isFloatingPointTy()) {
742 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
743 ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
744 if (Op.LHS.second && Op.RHS.second)
745 ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
746 else
747 ResI = Op.LHS.second ? Op.LHS.second
748 : Builder.CreateFNeg(Op.RHS.second, "sub.i");
749 assert(ResI && "Only one operand may be real!");
750 } else {
751 ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
752 assert(Op.LHS.second && Op.RHS.second &&
753 "Both operands of integer complex operators must be complex!");
754 ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
755 }
756 return ComplexPairTy(ResR, ResI);
757}
758
759/// Emit a libcall for a binary operation on complex types.
760ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
761 const BinOpInfo &Op) {
762 CallArgList Args;
763 Args.add(RValue::get(Op.LHS.first),
764 Op.Ty->castAs<ComplexType>()->getElementType());
765 Args.add(RValue::get(Op.LHS.second),
766 Op.Ty->castAs<ComplexType>()->getElementType());
767 Args.add(RValue::get(Op.RHS.first),
768 Op.Ty->castAs<ComplexType>()->getElementType());
769 Args.add(RValue::get(Op.RHS.second),
770 Op.Ty->castAs<ComplexType>()->getElementType());
771
772 // We *must* use the full CG function call building logic here because the
773 // complex type has special ABI handling. We also should not forget about
774 // special calling convention which may be used for compiler builtins.
775
776 // We create a function qualified type to state that this call does not have
777 // any exceptions.
778 FunctionProtoType::ExtProtoInfo EPI;
779 EPI = EPI.withExceptionSpec(
780 FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));
781 SmallVector<QualType, 4> ArgsQTys(
782 4, Op.Ty->castAs<ComplexType>()->getElementType());
783 QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
784 const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
785 Args, cast<FunctionType>(FQTy.getTypePtr()), false);
786
787 llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
788 llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(
789 FTy, LibCallName, llvm::AttributeList(), true);
790 CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
791
792 llvm::CallBase *Call;
793 RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
794 Call->setCallingConv(CGF.CGM.getRuntimeCC());
795 return Res.getComplexVal();
796}
797
798/// Lookup the libcall name for a given floating point type complex
799/// multiply.
800static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
801 switch (Ty->getTypeID()) {
802 default:
803 llvm_unreachable("Unsupported floating point type!");
804 case llvm::Type::HalfTyID:
805 return "__mulhc3";
806 case llvm::Type::FloatTyID:
807 return "__mulsc3";
808 case llvm::Type::DoubleTyID:
809 return "__muldc3";
810 case llvm::Type::PPC_FP128TyID:
811 return "__multc3";
812 case llvm::Type::X86_FP80TyID:
813 return "__mulxc3";
814 case llvm::Type::FP128TyID:
815 return "__multc3";
816 }
817}
818
819// See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
820// typed values.
821ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
822 using llvm::Value;
823 Value *ResR, *ResI;
824 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
825
826 if (Op.LHS.first->getType()->isFloatingPointTy()) {
827 // The general formulation is:
828 // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
829 //
830 // But we can fold away components which would be zero due to a real
831 // operand according to C11 Annex G.5.1p2.
832
833 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
834 if (Op.LHS.second && Op.RHS.second) {
835 // If both operands are complex, emit the core math directly, and then
836 // test for NaNs. If we find NaNs in the result, we delegate to a libcall
837 // to carefully re-compute the correct infinity representation if
838 // possible. The expectation is that the presence of NaNs here is
839 // *extremely* rare, and so the cost of the libcall is almost irrelevant.
840 // This is good, because the libcall re-computes the core multiplication
841 // exactly the same as we do here and re-tests for NaNs in order to be
842 // a generic complex*complex libcall.
843
844 // First compute the four products.
845 Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
846 Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
847 Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
848 Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
849
850 // The real part is the difference of the first two, the imaginary part is
851 // the sum of the second.
852 ResR = Builder.CreateFSub(AC, BD, "mul_r");
853 ResI = Builder.CreateFAdd(AD, BC, "mul_i");
854
855 if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||
856 Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||
857 Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)
858 return ComplexPairTy(ResR, ResI);
859
860 // Emit the test for the real part becoming NaN and create a branch to
861 // handle it. We test for NaN by comparing the number to itself.
862 Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
863 llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
864 llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
865 llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
866 llvm::BasicBlock *OrigBB = Branch->getParent();
867
868 // Give hint that we very much don't expect to see NaNs.
869 llvm::MDNode *BrWeight = MDHelper.createUnlikelyBranchWeights();
870 Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
871
872 // Now test the imaginary part and create its branch.
873 CGF.EmitBlock(INaNBB);
874 Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
875 llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
876 Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
877 Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
878
879 // Now emit the libcall on this slowest of the slow paths.
880 CGF.EmitBlock(LibCallBB);
881 Value *LibCallR, *LibCallI;
882 std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
883 getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
884 Builder.CreateBr(ContBB);
885
886 // Finally continue execution by phi-ing together the different
887 // computation paths.
888 CGF.EmitBlock(ContBB);
889 llvm::PHINode *RealPHI =
890 Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
891 RealPHI->addIncoming(ResR, OrigBB);
892 RealPHI->addIncoming(ResR, INaNBB);
893 RealPHI->addIncoming(LibCallR, LibCallBB);
894 llvm::PHINode *ImagPHI =
895 Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
896 ImagPHI->addIncoming(ResI, OrigBB);
897 ImagPHI->addIncoming(ResI, INaNBB);
898 ImagPHI->addIncoming(LibCallI, LibCallBB);
899 return ComplexPairTy(RealPHI, ImagPHI);
900 }
901 assert((Op.LHS.second || Op.RHS.second) &&
902 "At least one operand must be complex!");
903
904 // If either of the operands is a real rather than a complex, the
905 // imaginary component is ignored when computing the real component of the
906 // result.
907 ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
908
909 ResI = Op.LHS.second
910 ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
911 : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
912 } else {
913 assert(Op.LHS.second && Op.RHS.second &&
914 "Both operands of integer complex operators must be complex!");
915 Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
916 Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
917 ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
918
919 Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
920 Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
921 ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
922 }
923 return ComplexPairTy(ResR, ResI);
924}
925
926ComplexPairTy ComplexExprEmitter::EmitAlgebraicDiv(llvm::Value *LHSr,
927 llvm::Value *LHSi,
928 llvm::Value *RHSr,
929 llvm::Value *RHSi) {
930 // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
931 llvm::Value *DSTr, *DSTi;
932
933 llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
934 llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
935 llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
936
937 llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
938 llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
939 llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
940
941 llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
942 llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
943 llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
944
945 DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
946 DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
947 return ComplexPairTy(DSTr, DSTi);
948}
949
950// EmitFAbs - Emit a call to @llvm.fabs.
951static llvm::Value *EmitllvmFAbs(CodeGenFunction &CGF, llvm::Value *Value) {
952 llvm::Function *Func =
953 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Value->getType());
954 llvm::Value *Call = CGF.Builder.CreateCall(Func, Value);
955 return Call;
956}
957
958// EmitRangeReductionDiv - Implements Smith's algorithm for complex division.
959// SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
960ComplexPairTy ComplexExprEmitter::EmitRangeReductionDiv(llvm::Value *LHSr,
961 llvm::Value *LHSi,
962 llvm::Value *RHSr,
963 llvm::Value *RHSi) {
964 // FIXME: This could eventually be replaced by an LLVM intrinsic to
965 // avoid this long IR sequence.
966
967 // (a + ib) / (c + id) = (e + if)
968 llvm::Value *FAbsRHSr = EmitllvmFAbs(CGF, RHSr); // |c|
969 llvm::Value *FAbsRHSi = EmitllvmFAbs(CGF, RHSi); // |d|
970 // |c| >= |d|
971 llvm::Value *IsR = Builder.CreateFCmpUGT(FAbsRHSr, FAbsRHSi, "abs_cmp");
972
973 llvm::BasicBlock *TrueBB =
974 CGF.createBasicBlock("abs_rhsr_greater_or_equal_abs_rhsi");
975 llvm::BasicBlock *FalseBB =
976 CGF.createBasicBlock("abs_rhsr_less_than_abs_rhsi");
977 llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_div");
978 Builder.CreateCondBr(IsR, TrueBB, FalseBB);
979
980 CGF.EmitBlock(TrueBB);
981 // abs(c) >= abs(d)
982 // r = d/c
983 // tmp = c + rd
984 // e = (a + br)/tmp
985 // f = (b - ar)/tmp
986 llvm::Value *DdC = Builder.CreateFDiv(RHSi, RHSr); // r=d/c
987
988 llvm::Value *RD = Builder.CreateFMul(DdC, RHSi); // rd
989 llvm::Value *CpRD = Builder.CreateFAdd(RHSr, RD); // tmp=c+rd
990
991 llvm::Value *T3 = Builder.CreateFMul(LHSi, DdC); // br
992 llvm::Value *T4 = Builder.CreateFAdd(LHSr, T3); // a+br
993 llvm::Value *DSTTr = Builder.CreateFDiv(T4, CpRD); // (a+br)/tmp
994
995 llvm::Value *T5 = Builder.CreateFMul(LHSr, DdC); // ar
996 llvm::Value *T6 = Builder.CreateFSub(LHSi, T5); // b-ar
997 llvm::Value *DSTTi = Builder.CreateFDiv(T6, CpRD); // (b-ar)/tmp
998 Builder.CreateBr(ContBB);
999
1000 CGF.EmitBlock(FalseBB);
1001 // abs(c) < abs(d)
1002 // r = c/d
1003 // tmp = d + rc
1004 // e = (ar + b)/tmp
1005 // f = (br - a)/tmp
1006 llvm::Value *CdD = Builder.CreateFDiv(RHSr, RHSi); // r=c/d
1007
1008 llvm::Value *RC = Builder.CreateFMul(CdD, RHSr); // rc
1009 llvm::Value *DpRC = Builder.CreateFAdd(RHSi, RC); // tmp=d+rc
1010
1011 llvm::Value *T7 = Builder.CreateFMul(LHSr, CdD); // ar
1012 llvm::Value *T8 = Builder.CreateFAdd(T7, LHSi); // ar+b
1013 llvm::Value *DSTFr = Builder.CreateFDiv(T8, DpRC); // (ar+b)/tmp
1014
1015 llvm::Value *T9 = Builder.CreateFMul(LHSi, CdD); // br
1016 llvm::Value *T10 = Builder.CreateFSub(T9, LHSr); // br-a
1017 llvm::Value *DSTFi = Builder.CreateFDiv(T10, DpRC); // (br-a)/tmp
1018 Builder.CreateBr(ContBB);
1019
1020 // Phi together the computation paths.
1021 CGF.EmitBlock(ContBB);
1022 llvm::PHINode *VALr = Builder.CreatePHI(DSTTr->getType(), 2);
1023 VALr->addIncoming(DSTTr, TrueBB);
1024 VALr->addIncoming(DSTFr, FalseBB);
1025 llvm::PHINode *VALi = Builder.CreatePHI(DSTTi->getType(), 2);
1026 VALi->addIncoming(DSTTi, TrueBB);
1027 VALi->addIncoming(DSTFi, FalseBB);
1028 return ComplexPairTy(VALr, VALi);
1029}
1030
1031// See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
1032// typed values.
1033ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
1034 llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
1035 llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
1036 llvm::Value *DSTr, *DSTi;
1037 if (LHSr->getType()->isFloatingPointTy()) {
1038 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
1039 if (!RHSi) {
1040 assert(LHSi && "Can have at most one non-complex operand!");
1041
1042 DSTr = Builder.CreateFDiv(LHSr, RHSr);
1043 DSTi = Builder.CreateFDiv(LHSi, RHSr);
1044 return ComplexPairTy(DSTr, DSTi);
1045 }
1046 llvm::Value *OrigLHSi = LHSi;
1047 if (!LHSi)
1048 LHSi = llvm::Constant::getNullValue(RHSi->getType());
1049 if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||
1050 (Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted &&
1051 !FPHasBeenPromoted))
1052 return EmitRangeReductionDiv(LHSr, LHSi, RHSr, RHSi);
1053 else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||
1054 Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)
1055 return EmitAlgebraicDiv(LHSr, LHSi, RHSr, RHSi);
1056 // '-ffast-math' is used in the command line but followed by an
1057 // '-fno-cx-limited-range' or '-fcomplex-arithmetic=full'.
1058 else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Full) {
1059 LHSi = OrigLHSi;
1060 // If we have a complex operand on the RHS and FastMath is not allowed, we
1061 // delegate to a libcall to handle all of the complexities and minimize
1062 // underflow/overflow cases. When FastMath is allowed we construct the
1063 // divide inline using the same algorithm as for integer operands.
1064 BinOpInfo LibCallOp = Op;
1065 // If LHS was a real, supply a null imaginary part.
1066 if (!LHSi)
1067 LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
1068
1069 switch (LHSr->getType()->getTypeID()) {
1070 default:
1071 llvm_unreachable("Unsupported floating point type!");
1072 case llvm::Type::HalfTyID:
1073 return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
1074 case llvm::Type::FloatTyID:
1075 return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
1076 case llvm::Type::DoubleTyID:
1077 return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
1078 case llvm::Type::PPC_FP128TyID:
1079 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
1080 case llvm::Type::X86_FP80TyID:
1081 return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
1082 case llvm::Type::FP128TyID:
1083 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
1084 }
1085 } else {
1086 return EmitAlgebraicDiv(LHSr, LHSi, RHSr, RHSi);
1087 }
1088 } else {
1089 assert(Op.LHS.second && Op.RHS.second &&
1090 "Both operands of integer complex operators must be complex!");
1091 // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
1092 llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
1093 llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
1094 llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
1095
1096 llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
1097 llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
1098 llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
1099
1100 llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
1101 llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
1102 llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
1103
1104 if (Op.Ty->castAs<ComplexType>()
1105 ->getElementType()
1106 ->isUnsignedIntegerType()) {
1107 DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
1108 DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
1109 } else {
1110 DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
1111 DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
1112 }
1113 }
1114
1115 return ComplexPairTy(DSTr, DSTi);
1116}
1117
1119 QualType UnPromotionType) {
1120 llvm::Type *ComplexElementTy =
1121 ConvertType(UnPromotionType->castAs<ComplexType>()->getElementType());
1122 if (result.first)
1123 result.first =
1124 Builder.CreateFPTrunc(result.first, ComplexElementTy, "unpromotion");
1125 if (result.second)
1126 result.second =
1127 Builder.CreateFPTrunc(result.second, ComplexElementTy, "unpromotion");
1128 return result;
1129}
1130
1132 QualType PromotionType) {
1133 llvm::Type *ComplexElementTy =
1134 ConvertType(PromotionType->castAs<ComplexType>()->getElementType());
1135 if (result.first)
1136 result.first = Builder.CreateFPExt(result.first, ComplexElementTy, "ext");
1137 if (result.second)
1138 result.second = Builder.CreateFPExt(result.second, ComplexElementTy, "ext");
1139
1140 return result;
1141}
1142
1143ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E,
1144 QualType PromotionType) {
1145 E = E->IgnoreParens();
1146 if (auto BO = dyn_cast<BinaryOperator>(E)) {
1147 switch (BO->getOpcode()) {
1148#define HANDLE_BINOP(OP) \
1149 case BO_##OP: \
1150 return EmitBin##OP(EmitBinOps(BO, PromotionType));
1151 HANDLE_BINOP(Add)
1152 HANDLE_BINOP(Sub)
1153 HANDLE_BINOP(Mul)
1154 HANDLE_BINOP(Div)
1155#undef HANDLE_BINOP
1156 default:
1157 break;
1158 }
1159 } else if (auto UO = dyn_cast<UnaryOperator>(E)) {
1160 switch (UO->getOpcode()) {
1161 case UO_Minus:
1162 return VisitMinus(UO, PromotionType);
1163 case UO_Plus:
1164 return VisitPlus(UO, PromotionType);
1165 default:
1166 break;
1167 }
1168 }
1169 auto result = Visit(const_cast<Expr *>(E));
1170 if (!PromotionType.isNull())
1171 return CGF.EmitPromotedValue(result, PromotionType);
1172 else
1173 return result;
1174}
1175
1177 QualType DstTy) {
1178 return ComplexExprEmitter(*this).EmitPromoted(E, DstTy);
1179}
1180
1182ComplexExprEmitter::EmitPromotedComplexOperand(const Expr *E,
1183 QualType OverallPromotionType) {
1184 if (E->getType()->isAnyComplexType()) {
1185 if (!OverallPromotionType.isNull())
1186 return CGF.EmitPromotedComplexExpr(E, OverallPromotionType);
1187 else
1188 return Visit(const_cast<Expr *>(E));
1189 } else {
1190 if (!OverallPromotionType.isNull()) {
1191 QualType ComplexElementTy =
1192 OverallPromotionType->castAs<ComplexType>()->getElementType();
1193 return ComplexPairTy(CGF.EmitPromotedScalarExpr(E, ComplexElementTy),
1194 nullptr);
1195 } else {
1196 return ComplexPairTy(CGF.EmitScalarExpr(E), nullptr);
1197 }
1198 }
1199}
1200
1201ComplexExprEmitter::BinOpInfo
1202ComplexExprEmitter::EmitBinOps(const BinaryOperator *E,
1203 QualType PromotionType) {
1204 TestAndClearIgnoreReal();
1205 TestAndClearIgnoreImag();
1206 BinOpInfo Ops;
1207
1208 Ops.LHS = EmitPromotedComplexOperand(E->getLHS(), PromotionType);
1209 Ops.RHS = EmitPromotedComplexOperand(E->getRHS(), PromotionType);
1210 if (!PromotionType.isNull())
1211 Ops.Ty = PromotionType;
1212 else
1213 Ops.Ty = E->getType();
1214 Ops.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
1215 return Ops;
1216}
1217
1218LValue ComplexExprEmitter::EmitCompoundAssignLValue(
1219 const CompoundAssignOperator *E,
1220 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo &), RValue &Val) {
1221 TestAndClearIgnoreReal();
1222 TestAndClearIgnoreImag();
1223 QualType LHSTy = E->getLHS()->getType().getAtomicUnqualifiedType();
1224
1225 BinOpInfo OpInfo;
1226 OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
1227 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
1228
1229 const bool IsComplexDivisor = E->getOpcode() == BO_DivAssign &&
1230 E->getRHS()->getType()->isAnyComplexType();
1231
1232 // Load the RHS and LHS operands.
1233 // __block variables need to have the rhs evaluated first, plus this should
1234 // improve codegen a little.
1235 QualType PromotionTypeCR;
1236 PromotionTypeCR =
1237 getPromotionType(E->getStoredFPFeaturesOrDefault(),
1238 E->getComputationResultType(), IsComplexDivisor);
1239 if (PromotionTypeCR.isNull())
1240 PromotionTypeCR = E->getComputationResultType();
1241 OpInfo.Ty = PromotionTypeCR;
1242 QualType ComplexElementTy =
1243 OpInfo.Ty->castAs<ComplexType>()->getElementType();
1244 QualType PromotionTypeRHS =
1245 getPromotionType(E->getStoredFPFeaturesOrDefault(),
1246 E->getRHS()->getType(), IsComplexDivisor);
1247
1248 // The RHS should have been converted to the computation type.
1249 if (E->getRHS()->getType()->isRealFloatingType()) {
1250 if (!PromotionTypeRHS.isNull())
1251 OpInfo.RHS = ComplexPairTy(
1252 CGF.EmitPromotedScalarExpr(E->getRHS(), PromotionTypeRHS), nullptr);
1253 else {
1254 assert(CGF.getContext().hasSameUnqualifiedType(ComplexElementTy,
1255 E->getRHS()->getType()));
1256
1257 OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
1258 }
1259 } else {
1260 if (!PromotionTypeRHS.isNull()) {
1261 OpInfo.RHS = ComplexPairTy(
1262 CGF.EmitPromotedComplexExpr(E->getRHS(), PromotionTypeRHS));
1263 } else {
1264 assert(CGF.getContext().hasSameUnqualifiedType(OpInfo.Ty,
1265 E->getRHS()->getType()));
1266 OpInfo.RHS = Visit(E->getRHS());
1267 }
1268 }
1269
1270 LValue LHS = CGF.EmitLValue(E->getLHS());
1271
1272 // Load from the l-value and convert it.
1273 SourceLocation Loc = E->getExprLoc();
1274 QualType PromotionTypeLHS =
1275 getPromotionType(E->getStoredFPFeaturesOrDefault(),
1276 E->getComputationLHSType(), IsComplexDivisor);
1277 if (LHSTy->isAnyComplexType()) {
1278 ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
1279 if (!PromotionTypeLHS.isNull())
1280 OpInfo.LHS =
1281 EmitComplexToComplexCast(LHSVal, LHSTy, PromotionTypeLHS, Loc);
1282 else
1283 OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
1284 } else {
1285 llvm::Value *LHSVal = CGF.EmitLoadOfLValue(LHS, Loc).getScalarVal();
1286 // For floating point real operands we can directly pass the scalar form
1287 // to the binary operator emission and potentially get more efficient code.
1288 if (LHSTy->isRealFloatingType()) {
1289 QualType PromotedComplexElementTy;
1290 if (!PromotionTypeLHS.isNull()) {
1291 PromotedComplexElementTy =
1292 cast<ComplexType>(PromotionTypeLHS)->getElementType();
1293 if (!CGF.getContext().hasSameUnqualifiedType(PromotedComplexElementTy,
1294 PromotionTypeLHS))
1295 LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy,
1296 PromotedComplexElementTy, Loc);
1297 } else {
1298 if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
1299 LHSVal =
1300 CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
1301 }
1302 OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
1303 } else {
1304 OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
1305 }
1306 }
1307
1308 // Expand the binary operator.
1309 ComplexPairTy Result = (this->*Func)(OpInfo);
1310
1311 // Truncate the result and store it into the LHS lvalue.
1312 if (LHSTy->isAnyComplexType()) {
1313 ComplexPairTy ResVal =
1314 EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
1315 EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
1316 Val = RValue::getComplex(ResVal);
1317 } else {
1318 llvm::Value *ResVal =
1319 CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
1320 CGF.EmitStoreThroughLValue(RValue::get(ResVal), LHS, /*isInit*/ false);
1321 Val = RValue::get(ResVal);
1322 }
1323
1324 return LHS;
1325}
1326
1327// Compound assignments.
1328ComplexPairTy ComplexExprEmitter::EmitCompoundAssign(
1329 const CompoundAssignOperator *E,
1330 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo &)) {
1331 RValue Val;
1332 LValue LV = EmitCompoundAssignLValue(E, Func, Val);
1333
1334 // The result of an assignment in C is the assigned r-value.
1335 if (!CGF.getLangOpts().CPlusPlus)
1336 return Val.getComplexVal();
1337
1338 // If the lvalue is non-volatile, return the computed value of the assignment.
1339 if (!LV.isVolatileQualified())
1340 return Val.getComplexVal();
1341
1342 return EmitLoadOfLValue(LV, E->getExprLoc());
1343}
1344
1345LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
1346 ComplexPairTy &Val) {
1347 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1348 E->getRHS()->getType()) &&
1349 "Invalid assignment");
1350 TestAndClearIgnoreReal();
1351 TestAndClearIgnoreImag();
1352
1353 // Emit the RHS. __block variables need the RHS evaluated first.
1354 Val = Visit(E->getRHS());
1355
1356 // Compute the address to store into.
1357 LValue LHS = CGF.EmitLValue(E->getLHS());
1358
1359 // Store the result value into the LHS lvalue.
1360 EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
1361
1362 return LHS;
1363}
1364
1365ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1366 ComplexPairTy Val;
1367 ApplyAtomGroup Grp(CGF.getDebugInfo());
1368 LValue LV = EmitBinAssignLValue(E, Val);
1369
1370 // The result of an assignment in C is the assigned r-value.
1371 if (!CGF.getLangOpts().CPlusPlus)
1372 return Val;
1373
1374 // If the lvalue is non-volatile, return the computed value of the assignment.
1375 if (!LV.isVolatileQualified())
1376 return Val;
1377
1378 return EmitLoadOfLValue(LV, E->getExprLoc());
1379}
1380
1381ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
1382 CGF.EmitIgnoredExpr(E->getLHS());
1383 return Visit(E->getRHS());
1384}
1385
1386ComplexPairTy ComplexExprEmitter::VisitAbstractConditionalOperator(
1387 const AbstractConditionalOperator *E) {
1388 TestAndClearIgnoreReal();
1389 TestAndClearIgnoreImag();
1390 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1391 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1392 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1393
1394 // Bind the common expression if necessary.
1396
1398 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1399 CGF.getProfileCount(E));
1400
1401 eval.begin(CGF);
1402 CGF.EmitBlock(LHSBlock);
1404 ComplexPairTy LHS = Visit(E->getTrueExpr());
1405 LHSBlock = Builder.GetInsertBlock();
1406 CGF.EmitBranch(ContBlock);
1407 eval.end(CGF);
1408
1409 eval.begin(CGF);
1410 CGF.EmitBlock(RHSBlock);
1412 ComplexPairTy RHS = Visit(E->getFalseExpr());
1413 RHSBlock = Builder.GetInsertBlock();
1414 CGF.EmitBlock(ContBlock);
1415 eval.end(CGF);
1416
1417 // Create a PHI node for the real part.
1418 llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1419 RealPN->addIncoming(LHS.first, LHSBlock);
1420 RealPN->addIncoming(RHS.first, RHSBlock);
1421
1422 // Create a PHI node for the imaginary part.
1423 llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1424 ImagPN->addIncoming(LHS.second, LHSBlock);
1425 ImagPN->addIncoming(RHS.second, RHSBlock);
1426
1427 return ComplexPairTy(RealPN, ImagPN);
1428}
1429
1430ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1431 return Visit(E->getChosenSubExpr());
1432}
1433
1434ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1435 bool Ignore = TestAndClearIgnoreReal();
1436 (void)Ignore;
1437 assert(Ignore == false && "init list ignored");
1438 Ignore = TestAndClearIgnoreImag();
1439 (void)Ignore;
1440 assert(Ignore == false && "init list ignored");
1441
1442 if (E->getNumInits() == 2) {
1443 llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1444 llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1445 return ComplexPairTy(Real, Imag);
1446 } else if (E->getNumInits() == 1) {
1447 return Visit(E->getInit(0));
1448 }
1449
1450 // Empty init list initializes to null
1451 assert(E->getNumInits() == 0 && "Unexpected number of inits");
1452 QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1453 llvm::Type *LTy = CGF.ConvertType(Ty);
1454 llvm::Value *zeroConstant = llvm::Constant::getNullValue(LTy);
1455 return ComplexPairTy(zeroConstant, zeroConstant);
1456}
1457
1458ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1459 Address ArgValue = Address::invalid();
1460 RValue RV = CGF.EmitVAArg(E, ArgValue);
1461
1462 if (!ArgValue.isValid()) {
1463 CGF.ErrorUnsupported(E, "complex va_arg expression");
1464 llvm::Type *EltTy =
1465 CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1466 llvm::Value *U = llvm::PoisonValue::get(EltTy);
1467 return ComplexPairTy(U, U);
1468 }
1469
1470 return RV.getComplexVal();
1471}
1472
1473//===----------------------------------------------------------------------===//
1474// Entry Point into this File
1475//===----------------------------------------------------------------------===//
1476
1477/// EmitComplexExpr - Emit the computation of the specified expression of
1478/// complex type, ignoring the result.
1480 bool IgnoreImag) {
1481 assert(E && getComplexType(E->getType()) &&
1482 "Invalid complex expression to emit");
1483
1484 return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1485 .Visit(const_cast<Expr *>(E));
1486}
1487
1489 bool isInit) {
1490 assert(E && getComplexType(E->getType()) &&
1491 "Invalid complex expression to emit");
1492 ComplexExprEmitter Emitter(*this);
1493 ComplexPairTy Val = Emitter.Visit(const_cast<Expr *>(E));
1494 Emitter.EmitStoreOfComplex(Val, dest, isInit);
1495}
1496
1497/// EmitStoreOfComplex - Store a complex number into the specified l-value.
1499 bool isInit) {
1500 ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1501}
1502
1503/// EmitLoadOfComplex - Load a complex number from the specified address.
1505 SourceLocation loc) {
1506 return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1507}
1508
1510 assert(E->getOpcode() == BO_Assign);
1511 ComplexPairTy Val; // ignored
1512 LValue LVal = ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1513 if (getLangOpts().OpenMP)
1514 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1515 E->getLHS());
1516 return LVal;
1517}
1518
1519typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1520 const ComplexExprEmitter::BinOpInfo &);
1521
1523 switch (Op) {
1524 case BO_MulAssign:
1525 return &ComplexExprEmitter::EmitBinMul;
1526 case BO_DivAssign:
1527 return &ComplexExprEmitter::EmitBinDiv;
1528 case BO_SubAssign:
1529 return &ComplexExprEmitter::EmitBinSub;
1530 case BO_AddAssign:
1531 return &ComplexExprEmitter::EmitBinAdd;
1532 default:
1533 llvm_unreachable("unexpected complex compound assignment");
1534 }
1535}
1536
1538 const CompoundAssignOperator *E) {
1541 RValue Val;
1542 return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1543}
1544
1546 const CompoundAssignOperator *E, llvm::Value *&Result) {
1547 // Key Instructions: Don't need to create an atom group here; one will already
1548 // be active through scalar handling code.
1550 RValue Val;
1551 LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1552 Result = Val.getScalarVal();
1553 return Ret;
1554}
#define V(N, I)
static const ComplexType * getComplexType(QualType type)
Return the complex type that we are meant to emit.
CodeGenFunction::ComplexPairTy ComplexPairTy
static llvm::Value * EmitllvmFAbs(CodeGenFunction &CGF, llvm::Value *Value)
static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty)
Lookup the libcall name for a given floating point type complex multiply.
#define HANDLEBINOP(OP)
static CompoundFunc getComplexOp(BinaryOperatorKind op)
static const ComplexType * getComplexType(QualType type)
Return the complex type that we are meant to emit.
mlir::Value(ComplexExprEmitter::*)(const ComplexExprEmitter::BinOpInfo &) CompoundFunc
#define HANDLE_BINOP(OP)
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
CanQualType FloatTy
CanQualType LongDoubleTy
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:920
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:917
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4534
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4540
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4546
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
FPOptionsOverride getStoredFPFeaturesOrDefault() const
Get the store FPOptionsOverride or default if not stored.
Definition Expr.h:4248
SourceLocation getExprLoc() const
Definition Expr.h:4082
Expr * getRHS() const
Definition Expr.h:4093
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4254
Opcode getOpcode() const
Definition Expr.h:4086
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:287
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:305
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1603
CastKind getCastKind() const
Definition Expr.h:3723
bool changesVolatileQualification() const
Return.
Definition Expr.h:3813
Expr * getSubExpr()
Definition Expr.h:3729
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4887
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static Address invalid()
Definition Address.h:176
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition Address.h:218
bool isValid() const
Definition Address.h:177
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
All available information about a concrete callee.
Definition CGCall.h:63
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
CGFunctionInfo - Class to encapsulate the information about a function definition.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:274
void add(RValue rvalue, QualType type)
Definition CGCall.h:302
An object to manage conditionally-evaluated expressions.
LValue getReferenceLValue(CodeGenFunction &CGF, const Expr *RefExpr) const
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
An RAII object to record that we're evaluating a statement expression.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition CGObjC.cpp:591
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
Definition CGExpr.cpp:1352
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
llvm::Type * ConvertType(QualType T)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
Definition CGCall.cpp:6468
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7293
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
llvm::Value * EmitPromotedScalarExpr(const Expr *E, QualType PromotionType)
const LangOptions & getLangOpts() const
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
ComplexPairTy EmitPromotedComplexExpr(const Expr *E, QualType PromotionType)
LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, llvm::Value *&Result)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:251
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6406
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2497
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
Address emitAddrOfImagComponent(Address complex, QualType complexType)
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6359
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6345
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5355
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2738
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:557
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:912
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:660
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
Address emitAddrOfRealComponent(Address complex, QualType complexType)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
ComplexPairTy EmitUnPromotedValue(ComplexPairTy result, QualType PromotionType)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1934
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1707
llvm::LLVMContext & getLLVMContext()
ComplexPairTy EmitPromotedValue(ComplexPairTy result, QualType PromotionType)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:640
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1387
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1801
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments.
Definition CGCall.cpp:702
LValue - This represents an lvalue references.
Definition CGValue.h:183
bool isSimple() const
Definition CGValue.h:286
bool isVolatileQualified() const
Definition CGValue.h:297
Address getAddress() const
Definition CGValue.h:373
QualType getType() const
Definition CGValue.h:303
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:379
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
QualType getElementType() const
Definition TypeBase.h:3335
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4303
QualType getComputationLHSType() const
Definition Expr.h:4337
QualType getComputationResultType() const
Definition Expr.h:4340
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
const Expr * getSubExpr() const
Definition Expr.h:1065
const Expr * getSubExpr() const
Definition Expr.h:1746
unsigned getNumInits() const
Definition Expr.h:5332
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
Expr * getBase() const
Definition Expr.h:3444
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:1211
Expr * getSelectedExpr() const
Definition ExprCXX.h:4640
const Expr * getSubExpr() const
Definition Expr.h:2202
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
bool UseExcessPrecision(const ASTContext &Ctx)
Definition Type.cpp:1626
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1684
Encodes a location in the source.
CompoundStmt * getSubStmt()
Definition Expr.h:4615
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:736
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isAnyComplexType() const
Definition TypeBase.h:8803
bool isAtomicType() const
Definition TypeBase.h:8860
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isFloatingType() const
Definition Type.cpp:2342
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
Expr * getSubExpr() const
Definition Expr.h:2288
FPOptionsOverride getStoredFPFeaturesOrDefault() const
Get the store FPOptionsOverride or default if not stored.
Definition Expr.h:2392
QualType getType() const
Definition Value.cpp:237
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ComplexType > complexType
bool Null(InterpState &S, CodePtr OpPC, uint64_t Value, const Descriptor *Desc)
Definition Interp.h:2879
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1358
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
CastKind
CastKind - The kind of operation required for a conversion.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ EST_BasicNoexcept
noexcept
#define false
Definition stdbool.h:26
llvm::CallingConv::ID getRuntimeCC() const
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5469