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->castAs<ComplexType>()->getElementType();
511 DestType = DestType->castAs<ComplexType>()->getElementType();
512
513 // C99 6.3.1.6: When a value of complex type is converted to another
514 // complex type, both the real and imaginary parts follow the conversion
515 // rules for the corresponding real types.
516 if (Val.first)
517 Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
518 if (Val.second)
519 Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
520 return Val;
521}
522
523ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
524 QualType SrcType,
525 QualType DestType,
526 SourceLocation Loc) {
527 // Convert the input element to the element type of the complex.
528 DestType = DestType->castAs<ComplexType>()->getElementType();
529 Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
530
531 // Return (realval, 0).
532 return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
533}
534
535ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
536 QualType DestTy) {
537 switch (CK) {
538 case CK_Dependent:
539 llvm_unreachable("dependent cast kind in IR gen!");
540
541 // Atomic to non-atomic casts may be more than a no-op for some platforms and
542 // for some types.
543 case CK_AtomicToNonAtomic:
544 case CK_NonAtomicToAtomic:
545 case CK_NoOp:
546 case CK_LValueToRValue:
547 case CK_UserDefinedConversion:
548 return Visit(Op);
549
550 case CK_LValueBitCast: {
551 LValue origLV = CGF.EmitLValue(Op);
552 Address V = origLV.getAddress().withElementType(CGF.ConvertType(DestTy));
553 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
554 }
555
556 case CK_LValueToRValueBitCast: {
557 LValue SourceLVal = CGF.EmitLValue(Op);
558 Address Addr =
559 SourceLVal.getAddress().withElementType(CGF.ConvertTypeForMem(DestTy));
560 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
561 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
562 return EmitLoadOfLValue(DestLV, Op->getExprLoc());
563 }
564
565 case CK_BitCast:
566 case CK_BaseToDerived:
567 case CK_DerivedToBase:
568 case CK_UncheckedDerivedToBase:
569 case CK_Dynamic:
570 case CK_ToUnion:
571 case CK_ArrayToPointerDecay:
572 case CK_FunctionToPointerDecay:
573 case CK_NullToPointer:
574 case CK_NullToMemberPointer:
575 case CK_BaseToDerivedMemberPointer:
576 case CK_DerivedToBaseMemberPointer:
577 case CK_MemberPointerToBoolean:
578 case CK_ReinterpretMemberPointer:
579 case CK_ConstructorConversion:
580 case CK_IntegralToPointer:
581 case CK_PointerToIntegral:
582 case CK_PointerToBoolean:
583 case CK_ToVoid:
584 case CK_VectorSplat:
585 case CK_IntegralCast:
586 case CK_BooleanToSignedIntegral:
587 case CK_IntegralToBoolean:
588 case CK_IntegralToFloating:
589 case CK_FloatingToIntegral:
590 case CK_FloatingToBoolean:
591 case CK_FloatingCast:
592 case CK_CPointerToObjCPointerCast:
593 case CK_BlockPointerToObjCPointerCast:
594 case CK_AnyPointerToBlockPointerCast:
595 case CK_ObjCObjectLValueCast:
596 case CK_FloatingComplexToReal:
597 case CK_FloatingComplexToBoolean:
598 case CK_IntegralComplexToReal:
599 case CK_IntegralComplexToBoolean:
600 case CK_ARCProduceObject:
601 case CK_ARCConsumeObject:
602 case CK_ARCReclaimReturnedObject:
603 case CK_ARCExtendBlockObject:
604 case CK_CopyAndAutoreleaseBlockObject:
605 case CK_BuiltinFnToFnPtr:
606 case CK_ZeroToOCLOpaqueType:
607 case CK_AddressSpaceConversion:
608 case CK_IntToOCLSampler:
609 case CK_FloatingToFixedPoint:
610 case CK_FixedPointToFloating:
611 case CK_FixedPointCast:
612 case CK_FixedPointToBoolean:
613 case CK_FixedPointToIntegral:
614 case CK_IntegralToFixedPoint:
615 case CK_MatrixCast:
616 case CK_HLSLVectorTruncation:
617 case CK_HLSLMatrixTruncation:
618 case CK_HLSLArrayRValue:
619 case CK_HLSLElementwiseCast:
620 case CK_HLSLAggregateSplatCast:
621 llvm_unreachable("invalid cast kind for complex value");
622
623 case CK_FloatingRealToComplex:
624 case CK_IntegralRealToComplex: {
625 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
626 return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
627 DestTy, Op->getExprLoc());
628 }
629
630 case CK_FloatingComplexCast:
631 case CK_FloatingComplexToIntegralComplex:
632 case CK_IntegralComplexCast:
633 case CK_IntegralComplexToFloatingComplex: {
634 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
635 return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
636 Op->getExprLoc());
637 }
638 }
639
640 llvm_unreachable("unknown cast resulting in complex value");
641}
642
643ComplexPairTy ComplexExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
644 QualType PromotionType) {
645 QualType promotionTy =
646 PromotionType.isNull()
647 ? getPromotionType(E->getStoredFPFeaturesOrDefault(),
648 E->getSubExpr()->getType(),
649 /*IsComplexDivisor=*/false)
650 : PromotionType;
651 ComplexPairTy result = VisitPlus(E, promotionTy);
652 if (!promotionTy.isNull())
653 return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());
654 return result;
655}
656
657ComplexPairTy ComplexExprEmitter::VisitPlus(const UnaryOperator *E,
658 QualType PromotionType) {
659 TestAndClearIgnoreReal();
660 TestAndClearIgnoreImag();
661 if (!PromotionType.isNull())
662 return CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);
663 return Visit(E->getSubExpr());
664}
665
666ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
667 QualType PromotionType) {
668 QualType promotionTy =
669 PromotionType.isNull()
670 ? getPromotionType(E->getStoredFPFeaturesOrDefault(),
671 E->getSubExpr()->getType(),
672 /*IsComplexDivisor=*/false)
673 : PromotionType;
674 ComplexPairTy result = VisitMinus(E, promotionTy);
675 if (!promotionTy.isNull())
676 return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());
677 return result;
678}
679ComplexPairTy ComplexExprEmitter::VisitMinus(const UnaryOperator *E,
680 QualType PromotionType) {
681 TestAndClearIgnoreReal();
682 TestAndClearIgnoreImag();
683 ComplexPairTy Op;
684 if (!PromotionType.isNull())
685 Op = CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);
686 else
687 Op = Visit(E->getSubExpr());
688
689 llvm::Value *ResR, *ResI;
690 if (Op.first->getType()->isFloatingPointTy()) {
691 ResR = Builder.CreateFNeg(Op.first, "neg.r");
692 ResI = Builder.CreateFNeg(Op.second, "neg.i");
693 } else {
694 ResR = Builder.CreateNeg(Op.first, "neg.r");
695 ResI = Builder.CreateNeg(Op.second, "neg.i");
696 }
697 return ComplexPairTy(ResR, ResI);
698}
699
700ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
701 TestAndClearIgnoreReal();
702 TestAndClearIgnoreImag();
703 // ~(a+ib) = a + i*-b
704 ComplexPairTy Op = Visit(E->getSubExpr());
705 llvm::Value *ResI;
706 if (Op.second->getType()->isFloatingPointTy())
707 ResI = Builder.CreateFNeg(Op.second, "conj.i");
708 else
709 ResI = Builder.CreateNeg(Op.second, "conj.i");
710
711 return ComplexPairTy(Op.first, ResI);
712}
713
714ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
715 llvm::Value *ResR, *ResI;
716
717 if (Op.LHS.first->getType()->isFloatingPointTy()) {
718 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
719 ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
720 if (Op.LHS.second && Op.RHS.second)
721 ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
722 else
723 ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
724 assert(ResI && "Only one operand may be real!");
725 } else {
726 ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
727 assert(Op.LHS.second && Op.RHS.second &&
728 "Both operands of integer complex operators must be complex!");
729 ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
730 }
731 return ComplexPairTy(ResR, ResI);
732}
733
734ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
735 llvm::Value *ResR, *ResI;
736 if (Op.LHS.first->getType()->isFloatingPointTy()) {
737 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
738 ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
739 if (Op.LHS.second && Op.RHS.second)
740 ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
741 else
742 ResI = Op.LHS.second ? Op.LHS.second
743 : Builder.CreateFNeg(Op.RHS.second, "sub.i");
744 assert(ResI && "Only one operand may be real!");
745 } else {
746 ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
747 assert(Op.LHS.second && Op.RHS.second &&
748 "Both operands of integer complex operators must be complex!");
749 ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
750 }
751 return ComplexPairTy(ResR, ResI);
752}
753
754/// Emit a libcall for a binary operation on complex types.
755ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
756 const BinOpInfo &Op) {
757 CallArgList Args;
758 Args.add(RValue::get(Op.LHS.first),
759 Op.Ty->castAs<ComplexType>()->getElementType());
760 Args.add(RValue::get(Op.LHS.second),
761 Op.Ty->castAs<ComplexType>()->getElementType());
762 Args.add(RValue::get(Op.RHS.first),
763 Op.Ty->castAs<ComplexType>()->getElementType());
764 Args.add(RValue::get(Op.RHS.second),
765 Op.Ty->castAs<ComplexType>()->getElementType());
766
767 // We *must* use the full CG function call building logic here because the
768 // complex type has special ABI handling. We also should not forget about
769 // special calling convention which may be used for compiler builtins.
770
771 // We create a function qualified type to state that this call does not have
772 // any exceptions.
773 FunctionProtoType::ExtProtoInfo EPI;
774 EPI = EPI.withExceptionSpec(
775 FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));
776 SmallVector<QualType, 4> ArgsQTys(
777 4, Op.Ty->castAs<ComplexType>()->getElementType());
778 QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
779 const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
780 Args, cast<FunctionType>(FQTy.getTypePtr()), false);
781
782 llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
783 llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(
784 FTy, LibCallName, llvm::AttributeList(), true);
785 CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
786
787 llvm::CallBase *Call;
788 RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
789 Call->setCallingConv(CGF.CGM.getRuntimeCC());
790 return Res.getComplexVal();
791}
792
793/// Lookup the libcall name for a given floating point type complex
794/// multiply.
795static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
796 switch (Ty->getTypeID()) {
797 default:
798 llvm_unreachable("Unsupported floating point type!");
799 case llvm::Type::HalfTyID:
800 return "__mulhc3";
801 case llvm::Type::FloatTyID:
802 return "__mulsc3";
803 case llvm::Type::DoubleTyID:
804 return "__muldc3";
805 case llvm::Type::PPC_FP128TyID:
806 return "__multc3";
807 case llvm::Type::X86_FP80TyID:
808 return "__mulxc3";
809 case llvm::Type::FP128TyID:
810 return "__multc3";
811 }
812}
813
814// See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
815// typed values.
816ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
817 using llvm::Value;
818 Value *ResR, *ResI;
819 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
820
821 if (Op.LHS.first->getType()->isFloatingPointTy()) {
822 // The general formulation is:
823 // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
824 //
825 // But we can fold away components which would be zero due to a real
826 // operand according to C11 Annex G.5.1p2.
827
828 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
829 if (Op.LHS.second && Op.RHS.second) {
830 // If both operands are complex, emit the core math directly, and then
831 // test for NaNs. If we find NaNs in the result, we delegate to a libcall
832 // to carefully re-compute the correct infinity representation if
833 // possible. The expectation is that the presence of NaNs here is
834 // *extremely* rare, and so the cost of the libcall is almost irrelevant.
835 // This is good, because the libcall re-computes the core multiplication
836 // exactly the same as we do here and re-tests for NaNs in order to be
837 // a generic complex*complex libcall.
838
839 // First compute the four products.
840 Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
841 Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
842 Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
843 Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
844
845 // The real part is the difference of the first two, the imaginary part is
846 // the sum of the second.
847 ResR = Builder.CreateFSub(AC, BD, "mul_r");
848 ResI = Builder.CreateFAdd(AD, BC, "mul_i");
849
850 if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||
851 Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||
852 Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)
853 return ComplexPairTy(ResR, ResI);
854
855 // Emit the test for the real part becoming NaN and create a branch to
856 // handle it. We test for NaN by comparing the number to itself.
857 Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
858 llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
859 llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
860 llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
861 llvm::BasicBlock *OrigBB = Branch->getParent();
862
863 // Give hint that we very much don't expect to see NaNs.
864 llvm::MDNode *BrWeight = MDHelper.createUnlikelyBranchWeights();
865 Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
866
867 // Now test the imaginary part and create its branch.
868 CGF.EmitBlock(INaNBB);
869 Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
870 llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
871 Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
872 Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
873
874 // Now emit the libcall on this slowest of the slow paths.
875 CGF.EmitBlock(LibCallBB);
876 Value *LibCallR, *LibCallI;
877 std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
878 getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
879 Builder.CreateBr(ContBB);
880
881 // Finally continue execution by phi-ing together the different
882 // computation paths.
883 CGF.EmitBlock(ContBB);
884 llvm::PHINode *RealPHI =
885 Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
886 RealPHI->addIncoming(ResR, OrigBB);
887 RealPHI->addIncoming(ResR, INaNBB);
888 RealPHI->addIncoming(LibCallR, LibCallBB);
889 llvm::PHINode *ImagPHI =
890 Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
891 ImagPHI->addIncoming(ResI, OrigBB);
892 ImagPHI->addIncoming(ResI, INaNBB);
893 ImagPHI->addIncoming(LibCallI, LibCallBB);
894 return ComplexPairTy(RealPHI, ImagPHI);
895 }
896 assert((Op.LHS.second || Op.RHS.second) &&
897 "At least one operand must be complex!");
898
899 // If either of the operands is a real rather than a complex, the
900 // imaginary component is ignored when computing the real component of the
901 // result.
902 ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
903
904 ResI = Op.LHS.second
905 ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
906 : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
907 } else {
908 assert(Op.LHS.second && Op.RHS.second &&
909 "Both operands of integer complex operators must be complex!");
910 Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
911 Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
912 ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
913
914 Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
915 Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
916 ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
917 }
918 return ComplexPairTy(ResR, ResI);
919}
920
921ComplexPairTy ComplexExprEmitter::EmitAlgebraicDiv(llvm::Value *LHSr,
922 llvm::Value *LHSi,
923 llvm::Value *RHSr,
924 llvm::Value *RHSi) {
925 // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
926 llvm::Value *DSTr, *DSTi;
927
928 llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
929 llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
930 llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
931
932 llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
933 llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
934 llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
935
936 llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
937 llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
938 llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
939
940 DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
941 DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
942 return ComplexPairTy(DSTr, DSTi);
943}
944
945// EmitFAbs - Emit a call to @llvm.fabs.
946static llvm::Value *EmitllvmFAbs(CodeGenFunction &CGF, llvm::Value *Value) {
947 llvm::Function *Func =
948 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Value->getType());
949 llvm::Value *Call = CGF.Builder.CreateCall(Func, Value);
950 return Call;
951}
952
953// EmitRangeReductionDiv - Implements Smith's algorithm for complex division.
954// SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
955ComplexPairTy ComplexExprEmitter::EmitRangeReductionDiv(llvm::Value *LHSr,
956 llvm::Value *LHSi,
957 llvm::Value *RHSr,
958 llvm::Value *RHSi) {
959 // FIXME: This could eventually be replaced by an LLVM intrinsic to
960 // avoid this long IR sequence.
961
962 // (a + ib) / (c + id) = (e + if)
963 llvm::Value *FAbsRHSr = EmitllvmFAbs(CGF, RHSr); // |c|
964 llvm::Value *FAbsRHSi = EmitllvmFAbs(CGF, RHSi); // |d|
965 // |c| >= |d|
966 llvm::Value *IsR = Builder.CreateFCmpUGT(FAbsRHSr, FAbsRHSi, "abs_cmp");
967
968 llvm::BasicBlock *TrueBB =
969 CGF.createBasicBlock("abs_rhsr_greater_or_equal_abs_rhsi");
970 llvm::BasicBlock *FalseBB =
971 CGF.createBasicBlock("abs_rhsr_less_than_abs_rhsi");
972 llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_div");
973 Builder.CreateCondBr(IsR, TrueBB, FalseBB);
974
975 CGF.EmitBlock(TrueBB);
976 // abs(c) >= abs(d)
977 // r = d/c
978 // tmp = c + rd
979 // e = (a + br)/tmp
980 // f = (b - ar)/tmp
981 llvm::Value *DdC = Builder.CreateFDiv(RHSi, RHSr); // r=d/c
982
983 llvm::Value *RD = Builder.CreateFMul(DdC, RHSi); // rd
984 llvm::Value *CpRD = Builder.CreateFAdd(RHSr, RD); // tmp=c+rd
985
986 llvm::Value *T3 = Builder.CreateFMul(LHSi, DdC); // br
987 llvm::Value *T4 = Builder.CreateFAdd(LHSr, T3); // a+br
988 llvm::Value *DSTTr = Builder.CreateFDiv(T4, CpRD); // (a+br)/tmp
989
990 llvm::Value *T5 = Builder.CreateFMul(LHSr, DdC); // ar
991 llvm::Value *T6 = Builder.CreateFSub(LHSi, T5); // b-ar
992 llvm::Value *DSTTi = Builder.CreateFDiv(T6, CpRD); // (b-ar)/tmp
993 Builder.CreateBr(ContBB);
994
995 CGF.EmitBlock(FalseBB);
996 // abs(c) < abs(d)
997 // r = c/d
998 // tmp = d + rc
999 // e = (ar + b)/tmp
1000 // f = (br - a)/tmp
1001 llvm::Value *CdD = Builder.CreateFDiv(RHSr, RHSi); // r=c/d
1002
1003 llvm::Value *RC = Builder.CreateFMul(CdD, RHSr); // rc
1004 llvm::Value *DpRC = Builder.CreateFAdd(RHSi, RC); // tmp=d+rc
1005
1006 llvm::Value *T7 = Builder.CreateFMul(LHSr, CdD); // ar
1007 llvm::Value *T8 = Builder.CreateFAdd(T7, LHSi); // ar+b
1008 llvm::Value *DSTFr = Builder.CreateFDiv(T8, DpRC); // (ar+b)/tmp
1009
1010 llvm::Value *T9 = Builder.CreateFMul(LHSi, CdD); // br
1011 llvm::Value *T10 = Builder.CreateFSub(T9, LHSr); // br-a
1012 llvm::Value *DSTFi = Builder.CreateFDiv(T10, DpRC); // (br-a)/tmp
1013 Builder.CreateBr(ContBB);
1014
1015 // Phi together the computation paths.
1016 CGF.EmitBlock(ContBB);
1017 llvm::PHINode *VALr = Builder.CreatePHI(DSTTr->getType(), 2);
1018 VALr->addIncoming(DSTTr, TrueBB);
1019 VALr->addIncoming(DSTFr, FalseBB);
1020 llvm::PHINode *VALi = Builder.CreatePHI(DSTTi->getType(), 2);
1021 VALi->addIncoming(DSTTi, TrueBB);
1022 VALi->addIncoming(DSTFi, FalseBB);
1023 return ComplexPairTy(VALr, VALi);
1024}
1025
1026// See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
1027// typed values.
1028ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
1029 llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
1030 llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
1031 llvm::Value *DSTr, *DSTi;
1032 if (LHSr->getType()->isFloatingPointTy()) {
1033 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
1034 if (!RHSi) {
1035 assert(LHSi && "Can have at most one non-complex operand!");
1036
1037 DSTr = Builder.CreateFDiv(LHSr, RHSr);
1038 DSTi = Builder.CreateFDiv(LHSi, RHSr);
1039 return ComplexPairTy(DSTr, DSTi);
1040 }
1041 llvm::Value *OrigLHSi = LHSi;
1042 if (!LHSi)
1043 LHSi = llvm::Constant::getNullValue(RHSi->getType());
1044 if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||
1045 (Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted &&
1046 !FPHasBeenPromoted))
1047 return EmitRangeReductionDiv(LHSr, LHSi, RHSr, RHSi);
1048 else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||
1049 Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)
1050 return EmitAlgebraicDiv(LHSr, LHSi, RHSr, RHSi);
1051 // '-ffast-math' is used in the command line but followed by an
1052 // '-fno-cx-limited-range' or '-fcomplex-arithmetic=full'.
1053 else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Full) {
1054 LHSi = OrigLHSi;
1055 // If we have a complex operand on the RHS and FastMath is not allowed, we
1056 // delegate to a libcall to handle all of the complexities and minimize
1057 // underflow/overflow cases. When FastMath is allowed we construct the
1058 // divide inline using the same algorithm as for integer operands.
1059 BinOpInfo LibCallOp = Op;
1060 // If LHS was a real, supply a null imaginary part.
1061 if (!LHSi)
1062 LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
1063
1064 switch (LHSr->getType()->getTypeID()) {
1065 default:
1066 llvm_unreachable("Unsupported floating point type!");
1067 case llvm::Type::HalfTyID:
1068 return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
1069 case llvm::Type::FloatTyID:
1070 return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
1071 case llvm::Type::DoubleTyID:
1072 return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
1073 case llvm::Type::PPC_FP128TyID:
1074 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
1075 case llvm::Type::X86_FP80TyID:
1076 return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
1077 case llvm::Type::FP128TyID:
1078 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
1079 }
1080 } else {
1081 return EmitAlgebraicDiv(LHSr, LHSi, RHSr, RHSi);
1082 }
1083 } else {
1084 assert(Op.LHS.second && Op.RHS.second &&
1085 "Both operands of integer complex operators must be complex!");
1086 // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
1087 llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
1088 llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
1089 llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
1090
1091 llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
1092 llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
1093 llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
1094
1095 llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
1096 llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
1097 llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
1098
1099 if (Op.Ty->castAs<ComplexType>()
1100 ->getElementType()
1101 ->isUnsignedIntegerType()) {
1102 DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
1103 DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
1104 } else {
1105 DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
1106 DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
1107 }
1108 }
1109
1110 return ComplexPairTy(DSTr, DSTi);
1111}
1112
1114 QualType UnPromotionType) {
1115 llvm::Type *ComplexElementTy =
1116 ConvertType(UnPromotionType->castAs<ComplexType>()->getElementType());
1117 if (result.first)
1118 result.first =
1119 Builder.CreateFPTrunc(result.first, ComplexElementTy, "unpromotion");
1120 if (result.second)
1121 result.second =
1122 Builder.CreateFPTrunc(result.second, ComplexElementTy, "unpromotion");
1123 return result;
1124}
1125
1127 QualType PromotionType) {
1128 llvm::Type *ComplexElementTy =
1129 ConvertType(PromotionType->castAs<ComplexType>()->getElementType());
1130 if (result.first)
1131 result.first = Builder.CreateFPExt(result.first, ComplexElementTy, "ext");
1132 if (result.second)
1133 result.second = Builder.CreateFPExt(result.second, ComplexElementTy, "ext");
1134
1135 return result;
1136}
1137
1138ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E,
1139 QualType PromotionType) {
1140 E = E->IgnoreParens();
1141 if (auto BO = dyn_cast<BinaryOperator>(E)) {
1142 switch (BO->getOpcode()) {
1143#define HANDLE_BINOP(OP) \
1144 case BO_##OP: \
1145 return EmitBin##OP(EmitBinOps(BO, PromotionType));
1146 HANDLE_BINOP(Add)
1147 HANDLE_BINOP(Sub)
1148 HANDLE_BINOP(Mul)
1149 HANDLE_BINOP(Div)
1150#undef HANDLE_BINOP
1151 default:
1152 break;
1153 }
1154 } else if (auto UO = dyn_cast<UnaryOperator>(E)) {
1155 switch (UO->getOpcode()) {
1156 case UO_Minus:
1157 return VisitMinus(UO, PromotionType);
1158 case UO_Plus:
1159 return VisitPlus(UO, PromotionType);
1160 default:
1161 break;
1162 }
1163 }
1164 auto result = Visit(const_cast<Expr *>(E));
1165 if (!PromotionType.isNull())
1166 return CGF.EmitPromotedValue(result, PromotionType);
1167 else
1168 return result;
1169}
1170
1172 QualType DstTy) {
1173 return ComplexExprEmitter(*this).EmitPromoted(E, DstTy);
1174}
1175
1177ComplexExprEmitter::EmitPromotedComplexOperand(const Expr *E,
1178 QualType OverallPromotionType) {
1179 if (E->getType()->isAnyComplexType()) {
1180 if (!OverallPromotionType.isNull())
1181 return CGF.EmitPromotedComplexExpr(E, OverallPromotionType);
1182 else
1183 return Visit(const_cast<Expr *>(E));
1184 } else {
1185 if (!OverallPromotionType.isNull()) {
1186 QualType ComplexElementTy =
1187 OverallPromotionType->castAs<ComplexType>()->getElementType();
1188 return ComplexPairTy(CGF.EmitPromotedScalarExpr(E, ComplexElementTy),
1189 nullptr);
1190 } else {
1191 return ComplexPairTy(CGF.EmitScalarExpr(E), nullptr);
1192 }
1193 }
1194}
1195
1196ComplexExprEmitter::BinOpInfo
1197ComplexExprEmitter::EmitBinOps(const BinaryOperator *E,
1198 QualType PromotionType) {
1199 TestAndClearIgnoreReal();
1200 TestAndClearIgnoreImag();
1201 BinOpInfo Ops;
1202
1203 Ops.LHS = EmitPromotedComplexOperand(E->getLHS(), PromotionType);
1204 Ops.RHS = EmitPromotedComplexOperand(E->getRHS(), PromotionType);
1205 if (!PromotionType.isNull())
1206 Ops.Ty = PromotionType;
1207 else
1208 Ops.Ty = E->getType();
1209 Ops.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
1210 return Ops;
1211}
1212
1213LValue ComplexExprEmitter::EmitCompoundAssignLValue(
1214 const CompoundAssignOperator *E,
1215 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo &), RValue &Val) {
1216 TestAndClearIgnoreReal();
1217 TestAndClearIgnoreImag();
1218 QualType LHSTy = E->getLHS()->getType();
1219 if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
1220 LHSTy = AT->getValueType();
1221
1222 BinOpInfo OpInfo;
1223 OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
1224 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
1225
1226 const bool IsComplexDivisor = E->getOpcode() == BO_DivAssign &&
1227 E->getRHS()->getType()->isAnyComplexType();
1228
1229 // Load the RHS and LHS operands.
1230 // __block variables need to have the rhs evaluated first, plus this should
1231 // improve codegen a little.
1232 QualType PromotionTypeCR;
1233 PromotionTypeCR =
1234 getPromotionType(E->getStoredFPFeaturesOrDefault(),
1235 E->getComputationResultType(), IsComplexDivisor);
1236 if (PromotionTypeCR.isNull())
1237 PromotionTypeCR = E->getComputationResultType();
1238 OpInfo.Ty = PromotionTypeCR;
1239 QualType ComplexElementTy =
1240 OpInfo.Ty->castAs<ComplexType>()->getElementType();
1241 QualType PromotionTypeRHS =
1242 getPromotionType(E->getStoredFPFeaturesOrDefault(),
1243 E->getRHS()->getType(), IsComplexDivisor);
1244
1245 // The RHS should have been converted to the computation type.
1246 if (E->getRHS()->getType()->isRealFloatingType()) {
1247 if (!PromotionTypeRHS.isNull())
1248 OpInfo.RHS = ComplexPairTy(
1249 CGF.EmitPromotedScalarExpr(E->getRHS(), PromotionTypeRHS), nullptr);
1250 else {
1251 assert(CGF.getContext().hasSameUnqualifiedType(ComplexElementTy,
1252 E->getRHS()->getType()));
1253
1254 OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
1255 }
1256 } else {
1257 if (!PromotionTypeRHS.isNull()) {
1258 OpInfo.RHS = ComplexPairTy(
1259 CGF.EmitPromotedComplexExpr(E->getRHS(), PromotionTypeRHS));
1260 } else {
1261 assert(CGF.getContext().hasSameUnqualifiedType(OpInfo.Ty,
1262 E->getRHS()->getType()));
1263 OpInfo.RHS = Visit(E->getRHS());
1264 }
1265 }
1266
1267 LValue LHS = CGF.EmitLValue(E->getLHS());
1268
1269 // Load from the l-value and convert it.
1270 SourceLocation Loc = E->getExprLoc();
1271 QualType PromotionTypeLHS =
1272 getPromotionType(E->getStoredFPFeaturesOrDefault(),
1273 E->getComputationLHSType(), IsComplexDivisor);
1274 if (LHSTy->isAnyComplexType()) {
1275 ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
1276 if (!PromotionTypeLHS.isNull())
1277 OpInfo.LHS =
1278 EmitComplexToComplexCast(LHSVal, LHSTy, PromotionTypeLHS, Loc);
1279 else
1280 OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
1281 } else {
1282 llvm::Value *LHSVal = CGF.EmitLoadOfLValue(LHS, Loc).getScalarVal();
1283 // For floating point real operands we can directly pass the scalar form
1284 // to the binary operator emission and potentially get more efficient code.
1285 if (LHSTy->isRealFloatingType()) {
1286 QualType PromotedComplexElementTy;
1287 if (!PromotionTypeLHS.isNull()) {
1288 PromotedComplexElementTy =
1289 cast<ComplexType>(PromotionTypeLHS)->getElementType();
1290 if (!CGF.getContext().hasSameUnqualifiedType(PromotedComplexElementTy,
1291 PromotionTypeLHS))
1292 LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy,
1293 PromotedComplexElementTy, Loc);
1294 } else {
1295 if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
1296 LHSVal =
1297 CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
1298 }
1299 OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
1300 } else {
1301 OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
1302 }
1303 }
1304
1305 // Expand the binary operator.
1306 ComplexPairTy Result = (this->*Func)(OpInfo);
1307
1308 // Truncate the result and store it into the LHS lvalue.
1309 if (LHSTy->isAnyComplexType()) {
1310 ComplexPairTy ResVal =
1311 EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
1312 EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
1313 Val = RValue::getComplex(ResVal);
1314 } else {
1315 llvm::Value *ResVal =
1316 CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
1317 CGF.EmitStoreThroughLValue(RValue::get(ResVal), LHS, /*isInit*/ false);
1318 Val = RValue::get(ResVal);
1319 }
1320
1321 return LHS;
1322}
1323
1324// Compound assignments.
1325ComplexPairTy ComplexExprEmitter::EmitCompoundAssign(
1326 const CompoundAssignOperator *E,
1327 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo &)) {
1328 RValue Val;
1329 LValue LV = EmitCompoundAssignLValue(E, Func, Val);
1330
1331 // The result of an assignment in C is the assigned r-value.
1332 if (!CGF.getLangOpts().CPlusPlus)
1333 return Val.getComplexVal();
1334
1335 // If the lvalue is non-volatile, return the computed value of the assignment.
1336 if (!LV.isVolatileQualified())
1337 return Val.getComplexVal();
1338
1339 return EmitLoadOfLValue(LV, E->getExprLoc());
1340}
1341
1342LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
1343 ComplexPairTy &Val) {
1344 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1345 E->getRHS()->getType()) &&
1346 "Invalid assignment");
1347 TestAndClearIgnoreReal();
1348 TestAndClearIgnoreImag();
1349
1350 // Emit the RHS. __block variables need the RHS evaluated first.
1351 Val = Visit(E->getRHS());
1352
1353 // Compute the address to store into.
1354 LValue LHS = CGF.EmitLValue(E->getLHS());
1355
1356 // Store the result value into the LHS lvalue.
1357 EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
1358
1359 return LHS;
1360}
1361
1362ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1363 ComplexPairTy Val;
1364 ApplyAtomGroup Grp(CGF.getDebugInfo());
1365 LValue LV = EmitBinAssignLValue(E, Val);
1366
1367 // The result of an assignment in C is the assigned r-value.
1368 if (!CGF.getLangOpts().CPlusPlus)
1369 return Val;
1370
1371 // If the lvalue is non-volatile, return the computed value of the assignment.
1372 if (!LV.isVolatileQualified())
1373 return Val;
1374
1375 return EmitLoadOfLValue(LV, E->getExprLoc());
1376}
1377
1378ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
1379 CGF.EmitIgnoredExpr(E->getLHS());
1380 return Visit(E->getRHS());
1381}
1382
1383ComplexPairTy ComplexExprEmitter::VisitAbstractConditionalOperator(
1384 const AbstractConditionalOperator *E) {
1385 TestAndClearIgnoreReal();
1386 TestAndClearIgnoreImag();
1387 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1388 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1389 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1390
1391 // Bind the common expression if necessary.
1393
1395 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1396 CGF.getProfileCount(E));
1397
1398 eval.begin(CGF);
1399 CGF.EmitBlock(LHSBlock);
1401 ComplexPairTy LHS = Visit(E->getTrueExpr());
1402 LHSBlock = Builder.GetInsertBlock();
1403 CGF.EmitBranch(ContBlock);
1404 eval.end(CGF);
1405
1406 eval.begin(CGF);
1407 CGF.EmitBlock(RHSBlock);
1409 ComplexPairTy RHS = Visit(E->getFalseExpr());
1410 RHSBlock = Builder.GetInsertBlock();
1411 CGF.EmitBlock(ContBlock);
1412 eval.end(CGF);
1413
1414 // Create a PHI node for the real part.
1415 llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1416 RealPN->addIncoming(LHS.first, LHSBlock);
1417 RealPN->addIncoming(RHS.first, RHSBlock);
1418
1419 // Create a PHI node for the imaginary part.
1420 llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1421 ImagPN->addIncoming(LHS.second, LHSBlock);
1422 ImagPN->addIncoming(RHS.second, RHSBlock);
1423
1424 return ComplexPairTy(RealPN, ImagPN);
1425}
1426
1427ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1428 return Visit(E->getChosenSubExpr());
1429}
1430
1431ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1432 bool Ignore = TestAndClearIgnoreReal();
1433 (void)Ignore;
1434 assert(Ignore == false && "init list ignored");
1435 Ignore = TestAndClearIgnoreImag();
1436 (void)Ignore;
1437 assert(Ignore == false && "init list ignored");
1438
1439 if (E->getNumInits() == 2) {
1440 llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1441 llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1442 return ComplexPairTy(Real, Imag);
1443 } else if (E->getNumInits() == 1) {
1444 return Visit(E->getInit(0));
1445 }
1446
1447 // Empty init list initializes to null
1448 assert(E->getNumInits() == 0 && "Unexpected number of inits");
1449 QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1450 llvm::Type *LTy = CGF.ConvertType(Ty);
1451 llvm::Value *zeroConstant = llvm::Constant::getNullValue(LTy);
1452 return ComplexPairTy(zeroConstant, zeroConstant);
1453}
1454
1455ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1456 Address ArgValue = Address::invalid();
1457 RValue RV = CGF.EmitVAArg(E, ArgValue);
1458
1459 if (!ArgValue.isValid()) {
1460 CGF.ErrorUnsupported(E, "complex va_arg expression");
1461 llvm::Type *EltTy =
1462 CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1463 llvm::Value *U = llvm::PoisonValue::get(EltTy);
1464 return ComplexPairTy(U, U);
1465 }
1466
1467 return RV.getComplexVal();
1468}
1469
1470//===----------------------------------------------------------------------===//
1471// Entry Point into this File
1472//===----------------------------------------------------------------------===//
1473
1474/// EmitComplexExpr - Emit the computation of the specified expression of
1475/// complex type, ignoring the result.
1477 bool IgnoreImag) {
1478 assert(E && getComplexType(E->getType()) &&
1479 "Invalid complex expression to emit");
1480
1481 return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1482 .Visit(const_cast<Expr *>(E));
1483}
1484
1486 bool isInit) {
1487 assert(E && getComplexType(E->getType()) &&
1488 "Invalid complex expression to emit");
1489 ComplexExprEmitter Emitter(*this);
1490 ComplexPairTy Val = Emitter.Visit(const_cast<Expr *>(E));
1491 Emitter.EmitStoreOfComplex(Val, dest, isInit);
1492}
1493
1494/// EmitStoreOfComplex - Store a complex number into the specified l-value.
1496 bool isInit) {
1497 ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1498}
1499
1500/// EmitLoadOfComplex - Load a complex number from the specified address.
1502 SourceLocation loc) {
1503 return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1504}
1505
1507 assert(E->getOpcode() == BO_Assign);
1508 ComplexPairTy Val; // ignored
1509 LValue LVal = ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1510 if (getLangOpts().OpenMP)
1511 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1512 E->getLHS());
1513 return LVal;
1514}
1515
1516typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1517 const ComplexExprEmitter::BinOpInfo &);
1518
1520 switch (Op) {
1521 case BO_MulAssign:
1522 return &ComplexExprEmitter::EmitBinMul;
1523 case BO_DivAssign:
1524 return &ComplexExprEmitter::EmitBinDiv;
1525 case BO_SubAssign:
1526 return &ComplexExprEmitter::EmitBinSub;
1527 case BO_AddAssign:
1528 return &ComplexExprEmitter::EmitBinAdd;
1529 default:
1530 llvm_unreachable("unexpected complex compound assignment");
1531 }
1532}
1533
1535 const CompoundAssignOperator *E) {
1538 RValue Val;
1539 return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1540}
1541
1543 const CompoundAssignOperator *E, llvm::Value *&Result) {
1544 // Key Instructions: Don't need to create an atom group here; one will already
1545 // be active through scalar handling code.
1547 RValue Val;
1548 LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1549 Result = Val.getScalarVal();
1550 return Ret;
1551}
#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:573
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:6442
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:5340
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:1625
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:2357
bool isFloatingType() const
Definition Type.cpp:2341
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:2832
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1350
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