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