CGExprComplex.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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. #include "CGOpenMPRuntime.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "ConstantEmitter.h"
  16. #include "clang/AST/StmtVisitor.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/MDBuilder.h"
  21. #include "llvm/IR/Metadata.h"
  22. #include <algorithm>
  23. using namespace clang;
  24. using namespace CodeGen;
  25. //===----------------------------------------------------------------------===//
  26. // Complex Expression Emitter
  27. //===----------------------------------------------------------------------===//
  28. typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
  29. /// Return the complex type that we are meant to emit.
  30. static const ComplexType *getComplexType(QualType type) {
  31. type = type.getCanonicalType();
  32. if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
  33. return comp;
  34. } else {
  35. return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
  36. }
  37. }
  38. namespace {
  39. class ComplexExprEmitter
  40. : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
  41. CodeGenFunction &CGF;
  42. CGBuilderTy &Builder;
  43. bool IgnoreReal;
  44. bool IgnoreImag;
  45. public:
  46. ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
  47. : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
  48. }
  49. //===--------------------------------------------------------------------===//
  50. // Utilities
  51. //===--------------------------------------------------------------------===//
  52. bool TestAndClearIgnoreReal() {
  53. bool I = IgnoreReal;
  54. IgnoreReal = false;
  55. return I;
  56. }
  57. bool TestAndClearIgnoreImag() {
  58. bool I = IgnoreImag;
  59. IgnoreImag = false;
  60. return I;
  61. }
  62. /// EmitLoadOfLValue - Given an expression with complex type that represents a
  63. /// value l-value, this method emits the address of the l-value, then loads
  64. /// and returns the result.
  65. ComplexPairTy EmitLoadOfLValue(const Expr *E) {
  66. return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
  67. }
  68. ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
  69. /// EmitStoreOfComplex - Store the specified real/imag parts into the
  70. /// specified value pointer.
  71. void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
  72. /// Emit a cast from complex value Val to DestType.
  73. ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
  74. QualType DestType, SourceLocation Loc);
  75. /// Emit a cast from scalar value Val to DestType.
  76. ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
  77. QualType DestType, SourceLocation Loc);
  78. //===--------------------------------------------------------------------===//
  79. // Visitor Methods
  80. //===--------------------------------------------------------------------===//
  81. ComplexPairTy Visit(Expr *E) {
  82. ApplyDebugLocation DL(CGF, E);
  83. return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
  84. }
  85. ComplexPairTy VisitStmt(Stmt *S) {
  86. S->dump(llvm::errs(), CGF.getContext());
  87. llvm_unreachable("Stmt can't have complex result type!");
  88. }
  89. ComplexPairTy VisitExpr(Expr *S);
  90. ComplexPairTy VisitConstantExpr(ConstantExpr *E) {
  91. if (llvm::Constant *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E))
  92. return ComplexPairTy(Result->getAggregateElement(0U),
  93. Result->getAggregateElement(1U));
  94. return Visit(E->getSubExpr());
  95. }
  96. ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
  97. ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  98. return Visit(GE->getResultExpr());
  99. }
  100. ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
  101. ComplexPairTy
  102. VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
  103. return Visit(PE->getReplacement());
  104. }
  105. ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {
  106. return CGF.EmitCoawaitExpr(*S).getComplexVal();
  107. }
  108. ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {
  109. return CGF.EmitCoyieldExpr(*S).getComplexVal();
  110. }
  111. ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {
  112. return Visit(E->getSubExpr());
  113. }
  114. ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,
  115. Expr *E) {
  116. assert(Constant && "not a constant");
  117. if (Constant.isReference())
  118. return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),
  119. E->getExprLoc());
  120. llvm::Constant *pair = Constant.getValue();
  121. return ComplexPairTy(pair->getAggregateElement(0U),
  122. pair->getAggregateElement(1U));
  123. }
  124. // l-values.
  125. ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
  126. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
  127. return emitConstant(Constant, E);
  128. return EmitLoadOfLValue(E);
  129. }
  130. ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  131. return EmitLoadOfLValue(E);
  132. }
  133. ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
  134. return CGF.EmitObjCMessageExpr(E).getComplexVal();
  135. }
  136. ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
  137. ComplexPairTy VisitMemberExpr(MemberExpr *ME) {
  138. if (CodeGenFunction::ConstantEmission Constant =
  139. CGF.tryEmitAsConstant(ME)) {
  140. CGF.EmitIgnoredExpr(ME->getBase());
  141. return emitConstant(Constant, ME);
  142. }
  143. return EmitLoadOfLValue(ME);
  144. }
  145. ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  146. if (E->isGLValue())
  147. return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
  148. E->getExprLoc());
  149. return CGF.getOrCreateOpaqueRValueMapping(E).getComplexVal();
  150. }
  151. ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  152. return CGF.EmitPseudoObjectRValue(E).getComplexVal();
  153. }
  154. // FIXME: CompoundLiteralExpr
  155. ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
  156. ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
  157. // Unlike for scalars, we don't have to worry about function->ptr demotion
  158. // here.
  159. return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
  160. }
  161. ComplexPairTy VisitCastExpr(CastExpr *E) {
  162. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
  163. CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
  164. return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
  165. }
  166. ComplexPairTy VisitCallExpr(const CallExpr *E);
  167. ComplexPairTy VisitStmtExpr(const StmtExpr *E);
  168. // Operators.
  169. ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
  170. bool isInc, bool isPre) {
  171. LValue LV = CGF.EmitLValue(E->getSubExpr());
  172. return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
  173. }
  174. ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
  175. return VisitPrePostIncDec(E, false, false);
  176. }
  177. ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
  178. return VisitPrePostIncDec(E, true, false);
  179. }
  180. ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
  181. return VisitPrePostIncDec(E, false, true);
  182. }
  183. ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
  184. return VisitPrePostIncDec(E, true, true);
  185. }
  186. ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
  187. ComplexPairTy VisitUnaryPlus (const UnaryOperator *E) {
  188. TestAndClearIgnoreReal();
  189. TestAndClearIgnoreImag();
  190. return Visit(E->getSubExpr());
  191. }
  192. ComplexPairTy VisitUnaryMinus (const UnaryOperator *E);
  193. ComplexPairTy VisitUnaryNot (const UnaryOperator *E);
  194. // LNot,Real,Imag never return complex.
  195. ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
  196. return Visit(E->getSubExpr());
  197. }
  198. ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  199. CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
  200. return Visit(DAE->getExpr());
  201. }
  202. ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  203. CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
  204. return Visit(DIE->getExpr());
  205. }
  206. ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
  207. CodeGenFunction::RunCleanupsScope Scope(CGF);
  208. ComplexPairTy Vals = Visit(E->getSubExpr());
  209. // Defend against dominance problems caused by jumps out of expression
  210. // evaluation through the shared cleanup block.
  211. Scope.ForceCleanup({&Vals.first, &Vals.second});
  212. return Vals;
  213. }
  214. ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
  215. assert(E->getType()->isAnyComplexType() && "Expected complex type!");
  216. QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
  217. llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
  218. return ComplexPairTy(Null, Null);
  219. }
  220. ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
  221. assert(E->getType()->isAnyComplexType() && "Expected complex type!");
  222. QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
  223. llvm::Constant *Null =
  224. llvm::Constant::getNullValue(CGF.ConvertType(Elem));
  225. return ComplexPairTy(Null, Null);
  226. }
  227. struct BinOpInfo {
  228. ComplexPairTy LHS;
  229. ComplexPairTy RHS;
  230. QualType Ty; // Computation Type.
  231. };
  232. BinOpInfo EmitBinOps(const BinaryOperator *E);
  233. LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
  234. ComplexPairTy (ComplexExprEmitter::*Func)
  235. (const BinOpInfo &),
  236. RValue &Val);
  237. ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,
  238. ComplexPairTy (ComplexExprEmitter::*Func)
  239. (const BinOpInfo &));
  240. ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
  241. ComplexPairTy EmitBinSub(const BinOpInfo &Op);
  242. ComplexPairTy EmitBinMul(const BinOpInfo &Op);
  243. ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
  244. ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
  245. const BinOpInfo &Op);
  246. ComplexPairTy VisitBinAdd(const BinaryOperator *E) {
  247. return EmitBinAdd(EmitBinOps(E));
  248. }
  249. ComplexPairTy VisitBinSub(const BinaryOperator *E) {
  250. return EmitBinSub(EmitBinOps(E));
  251. }
  252. ComplexPairTy VisitBinMul(const BinaryOperator *E) {
  253. return EmitBinMul(EmitBinOps(E));
  254. }
  255. ComplexPairTy VisitBinDiv(const BinaryOperator *E) {
  256. return EmitBinDiv(EmitBinOps(E));
  257. }
  258. ComplexPairTy VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
  259. return Visit(E->getSemanticForm());
  260. }
  261. // Compound assignments.
  262. ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
  263. return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
  264. }
  265. ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
  266. return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
  267. }
  268. ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
  269. return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
  270. }
  271. ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
  272. return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
  273. }
  274. // GCC rejects rem/and/or/xor for integer complex.
  275. // Logical and/or always return int, never complex.
  276. // No comparisons produce a complex result.
  277. LValue EmitBinAssignLValue(const BinaryOperator *E,
  278. ComplexPairTy &Val);
  279. ComplexPairTy VisitBinAssign (const BinaryOperator *E);
  280. ComplexPairTy VisitBinComma (const BinaryOperator *E);
  281. ComplexPairTy
  282. VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
  283. ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
  284. ComplexPairTy VisitInitListExpr(InitListExpr *E);
  285. ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  286. return EmitLoadOfLValue(E);
  287. }
  288. ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
  289. ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
  290. return CGF.EmitAtomicExpr(E).getComplexVal();
  291. }
  292. };
  293. } // end anonymous namespace.
  294. //===----------------------------------------------------------------------===//
  295. // Utilities
  296. //===----------------------------------------------------------------------===//
  297. Address CodeGenFunction::emitAddrOfRealComponent(Address addr,
  298. QualType complexType) {
  299. return Builder.CreateStructGEP(addr, 0, addr.getName() + ".realp");
  300. }
  301. Address CodeGenFunction::emitAddrOfImagComponent(Address addr,
  302. QualType complexType) {
  303. return Builder.CreateStructGEP(addr, 1, addr.getName() + ".imagp");
  304. }
  305. /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
  306. /// load the real and imaginary pieces, returning them as Real/Imag.
  307. ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
  308. SourceLocation loc) {
  309. assert(lvalue.isSimple() && "non-simple complex l-value?");
  310. if (lvalue.getType()->isAtomicType())
  311. return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
  312. Address SrcPtr = lvalue.getAddress(CGF);
  313. bool isVolatile = lvalue.isVolatileQualified();
  314. llvm::Value *Real = nullptr, *Imag = nullptr;
  315. if (!IgnoreReal || isVolatile) {
  316. Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
  317. Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
  318. }
  319. if (!IgnoreImag || isVolatile) {
  320. Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
  321. Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
  322. }
  323. return ComplexPairTy(Real, Imag);
  324. }
  325. /// EmitStoreOfComplex - Store the specified real/imag parts into the
  326. /// specified value pointer.
  327. void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
  328. bool isInit) {
  329. if (lvalue.getType()->isAtomicType() ||
  330. (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
  331. return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
  332. Address Ptr = lvalue.getAddress(CGF);
  333. Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
  334. Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
  335. Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
  336. Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
  337. }
  338. //===----------------------------------------------------------------------===//
  339. // Visitor Methods
  340. //===----------------------------------------------------------------------===//
  341. ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
  342. CGF.ErrorUnsupported(E, "complex expression");
  343. llvm::Type *EltTy =
  344. CGF.ConvertType(getComplexType(E->getType())->getElementType());
  345. llvm::Value *U = llvm::UndefValue::get(EltTy);
  346. return ComplexPairTy(U, U);
  347. }
  348. ComplexPairTy ComplexExprEmitter::
  349. VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
  350. llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
  351. return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
  352. }
  353. ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
  354. if (E->getCallReturnType(CGF.getContext())->isReferenceType())
  355. return EmitLoadOfLValue(E);
  356. return CGF.EmitCallExpr(E).getComplexVal();
  357. }
  358. ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  359. CodeGenFunction::StmtExprEvaluation eval(CGF);
  360. Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
  361. assert(RetAlloca.isValid() && "Expected complex return value");
  362. return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
  363. E->getExprLoc());
  364. }
  365. /// Emit a cast from complex value Val to DestType.
  366. ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
  367. QualType SrcType,
  368. QualType DestType,
  369. SourceLocation Loc) {
  370. // Get the src/dest element type.
  371. SrcType = SrcType->castAs<ComplexType>()->getElementType();
  372. DestType = DestType->castAs<ComplexType>()->getElementType();
  373. // C99 6.3.1.6: When a value of complex type is converted to another
  374. // complex type, both the real and imaginary parts follow the conversion
  375. // rules for the corresponding real types.
  376. if (Val.first)
  377. Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
  378. if (Val.second)
  379. Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
  380. return Val;
  381. }
  382. ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
  383. QualType SrcType,
  384. QualType DestType,
  385. SourceLocation Loc) {
  386. // Convert the input element to the element type of the complex.
  387. DestType = DestType->castAs<ComplexType>()->getElementType();
  388. Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
  389. // Return (realval, 0).
  390. return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
  391. }
  392. ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
  393. QualType DestTy) {
  394. switch (CK) {
  395. case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
  396. // Atomic to non-atomic casts may be more than a no-op for some platforms and
  397. // for some types.
  398. case CK_AtomicToNonAtomic:
  399. case CK_NonAtomicToAtomic:
  400. case CK_NoOp:
  401. case CK_LValueToRValue:
  402. case CK_UserDefinedConversion:
  403. return Visit(Op);
  404. case CK_LValueBitCast: {
  405. LValue origLV = CGF.EmitLValue(Op);
  406. Address V = origLV.getAddress(CGF);
  407. V = Builder.CreateElementBitCast(V, CGF.ConvertType(DestTy));
  408. return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
  409. }
  410. case CK_LValueToRValueBitCast: {
  411. LValue SourceLVal = CGF.EmitLValue(Op);
  412. Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
  413. CGF.ConvertTypeForMem(DestTy));
  414. LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
  415. DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
  416. return EmitLoadOfLValue(DestLV, Op->getExprLoc());
  417. }
  418. case CK_BitCast:
  419. case CK_BaseToDerived:
  420. case CK_DerivedToBase:
  421. case CK_UncheckedDerivedToBase:
  422. case CK_Dynamic:
  423. case CK_ToUnion:
  424. case CK_ArrayToPointerDecay:
  425. case CK_FunctionToPointerDecay:
  426. case CK_NullToPointer:
  427. case CK_NullToMemberPointer:
  428. case CK_BaseToDerivedMemberPointer:
  429. case CK_DerivedToBaseMemberPointer:
  430. case CK_MemberPointerToBoolean:
  431. case CK_ReinterpretMemberPointer:
  432. case CK_ConstructorConversion:
  433. case CK_IntegralToPointer:
  434. case CK_PointerToIntegral:
  435. case CK_PointerToBoolean:
  436. case CK_ToVoid:
  437. case CK_VectorSplat:
  438. case CK_IntegralCast:
  439. case CK_BooleanToSignedIntegral:
  440. case CK_IntegralToBoolean:
  441. case CK_IntegralToFloating:
  442. case CK_FloatingToIntegral:
  443. case CK_FloatingToBoolean:
  444. case CK_FloatingCast:
  445. case CK_CPointerToObjCPointerCast:
  446. case CK_BlockPointerToObjCPointerCast:
  447. case CK_AnyPointerToBlockPointerCast:
  448. case CK_ObjCObjectLValueCast:
  449. case CK_FloatingComplexToReal:
  450. case CK_FloatingComplexToBoolean:
  451. case CK_IntegralComplexToReal:
  452. case CK_IntegralComplexToBoolean:
  453. case CK_ARCProduceObject:
  454. case CK_ARCConsumeObject:
  455. case CK_ARCReclaimReturnedObject:
  456. case CK_ARCExtendBlockObject:
  457. case CK_CopyAndAutoreleaseBlockObject:
  458. case CK_BuiltinFnToFnPtr:
  459. case CK_ZeroToOCLOpaqueType:
  460. case CK_AddressSpaceConversion:
  461. case CK_IntToOCLSampler:
  462. case CK_FloatingToFixedPoint:
  463. case CK_FixedPointToFloating:
  464. case CK_FixedPointCast:
  465. case CK_FixedPointToBoolean:
  466. case CK_FixedPointToIntegral:
  467. case CK_IntegralToFixedPoint:
  468. case CK_MatrixCast:
  469. llvm_unreachable("invalid cast kind for complex value");
  470. case CK_FloatingRealToComplex:
  471. case CK_IntegralRealToComplex: {
  472. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
  473. return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
  474. DestTy, Op->getExprLoc());
  475. }
  476. case CK_FloatingComplexCast:
  477. case CK_FloatingComplexToIntegralComplex:
  478. case CK_IntegralComplexCast:
  479. case CK_IntegralComplexToFloatingComplex: {
  480. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
  481. return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
  482. Op->getExprLoc());
  483. }
  484. }
  485. llvm_unreachable("unknown cast resulting in complex value");
  486. }
  487. ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
  488. TestAndClearIgnoreReal();
  489. TestAndClearIgnoreImag();
  490. ComplexPairTy Op = Visit(E->getSubExpr());
  491. llvm::Value *ResR, *ResI;
  492. if (Op.first->getType()->isFloatingPointTy()) {
  493. ResR = Builder.CreateFNeg(Op.first, "neg.r");
  494. ResI = Builder.CreateFNeg(Op.second, "neg.i");
  495. } else {
  496. ResR = Builder.CreateNeg(Op.first, "neg.r");
  497. ResI = Builder.CreateNeg(Op.second, "neg.i");
  498. }
  499. return ComplexPairTy(ResR, ResI);
  500. }
  501. ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
  502. TestAndClearIgnoreReal();
  503. TestAndClearIgnoreImag();
  504. // ~(a+ib) = a + i*-b
  505. ComplexPairTy Op = Visit(E->getSubExpr());
  506. llvm::Value *ResI;
  507. if (Op.second->getType()->isFloatingPointTy())
  508. ResI = Builder.CreateFNeg(Op.second, "conj.i");
  509. else
  510. ResI = Builder.CreateNeg(Op.second, "conj.i");
  511. return ComplexPairTy(Op.first, ResI);
  512. }
  513. ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
  514. llvm::Value *ResR, *ResI;
  515. if (Op.LHS.first->getType()->isFloatingPointTy()) {
  516. ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
  517. if (Op.LHS.second && Op.RHS.second)
  518. ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
  519. else
  520. ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
  521. assert(ResI && "Only one operand may be real!");
  522. } else {
  523. ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
  524. assert(Op.LHS.second && Op.RHS.second &&
  525. "Both operands of integer complex operators must be complex!");
  526. ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
  527. }
  528. return ComplexPairTy(ResR, ResI);
  529. }
  530. ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
  531. llvm::Value *ResR, *ResI;
  532. if (Op.LHS.first->getType()->isFloatingPointTy()) {
  533. ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
  534. if (Op.LHS.second && Op.RHS.second)
  535. ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
  536. else
  537. ResI = Op.LHS.second ? Op.LHS.second
  538. : Builder.CreateFNeg(Op.RHS.second, "sub.i");
  539. assert(ResI && "Only one operand may be real!");
  540. } else {
  541. ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
  542. assert(Op.LHS.second && Op.RHS.second &&
  543. "Both operands of integer complex operators must be complex!");
  544. ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
  545. }
  546. return ComplexPairTy(ResR, ResI);
  547. }
  548. /// Emit a libcall for a binary operation on complex types.
  549. ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
  550. const BinOpInfo &Op) {
  551. CallArgList Args;
  552. Args.add(RValue::get(Op.LHS.first),
  553. Op.Ty->castAs<ComplexType>()->getElementType());
  554. Args.add(RValue::get(Op.LHS.second),
  555. Op.Ty->castAs<ComplexType>()->getElementType());
  556. Args.add(RValue::get(Op.RHS.first),
  557. Op.Ty->castAs<ComplexType>()->getElementType());
  558. Args.add(RValue::get(Op.RHS.second),
  559. Op.Ty->castAs<ComplexType>()->getElementType());
  560. // We *must* use the full CG function call building logic here because the
  561. // complex type has special ABI handling. We also should not forget about
  562. // special calling convention which may be used for compiler builtins.
  563. // We create a function qualified type to state that this call does not have
  564. // any exceptions.
  565. FunctionProtoType::ExtProtoInfo EPI;
  566. EPI = EPI.withExceptionSpec(
  567. FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));
  568. SmallVector<QualType, 4> ArgsQTys(
  569. 4, Op.Ty->castAs<ComplexType>()->getElementType());
  570. QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
  571. const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
  572. Args, cast<FunctionType>(FQTy.getTypePtr()), false);
  573. llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
  574. llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(
  575. FTy, LibCallName, llvm::AttributeList(), true);
  576. CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
  577. llvm::CallBase *Call;
  578. RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
  579. Call->setCallingConv(CGF.CGM.getRuntimeCC());
  580. return Res.getComplexVal();
  581. }
  582. /// Lookup the libcall name for a given floating point type complex
  583. /// multiply.
  584. static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
  585. switch (Ty->getTypeID()) {
  586. default:
  587. llvm_unreachable("Unsupported floating point type!");
  588. case llvm::Type::HalfTyID:
  589. return "__mulhc3";
  590. case llvm::Type::FloatTyID:
  591. return "__mulsc3";
  592. case llvm::Type::DoubleTyID:
  593. return "__muldc3";
  594. case llvm::Type::PPC_FP128TyID:
  595. return "__multc3";
  596. case llvm::Type::X86_FP80TyID:
  597. return "__mulxc3";
  598. case llvm::Type::FP128TyID:
  599. return "__multc3";
  600. }
  601. }
  602. // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
  603. // typed values.
  604. ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
  605. using llvm::Value;
  606. Value *ResR, *ResI;
  607. llvm::MDBuilder MDHelper(CGF.getLLVMContext());
  608. if (Op.LHS.first->getType()->isFloatingPointTy()) {
  609. // The general formulation is:
  610. // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
  611. //
  612. // But we can fold away components which would be zero due to a real
  613. // operand according to C11 Annex G.5.1p2.
  614. // FIXME: C11 also provides for imaginary types which would allow folding
  615. // still more of this within the type system.
  616. if (Op.LHS.second && Op.RHS.second) {
  617. // If both operands are complex, emit the core math directly, and then
  618. // test for NaNs. If we find NaNs in the result, we delegate to a libcall
  619. // to carefully re-compute the correct infinity representation if
  620. // possible. The expectation is that the presence of NaNs here is
  621. // *extremely* rare, and so the cost of the libcall is almost irrelevant.
  622. // This is good, because the libcall re-computes the core multiplication
  623. // exactly the same as we do here and re-tests for NaNs in order to be
  624. // a generic complex*complex libcall.
  625. // First compute the four products.
  626. Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
  627. Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
  628. Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
  629. Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
  630. // The real part is the difference of the first two, the imaginary part is
  631. // the sum of the second.
  632. ResR = Builder.CreateFSub(AC, BD, "mul_r");
  633. ResI = Builder.CreateFAdd(AD, BC, "mul_i");
  634. // Emit the test for the real part becoming NaN and create a branch to
  635. // handle it. We test for NaN by comparing the number to itself.
  636. Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
  637. llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
  638. llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
  639. llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
  640. llvm::BasicBlock *OrigBB = Branch->getParent();
  641. // Give hint that we very much don't expect to see NaNs.
  642. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  643. llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
  644. Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
  645. // Now test the imaginary part and create its branch.
  646. CGF.EmitBlock(INaNBB);
  647. Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
  648. llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
  649. Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
  650. Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
  651. // Now emit the libcall on this slowest of the slow paths.
  652. CGF.EmitBlock(LibCallBB);
  653. Value *LibCallR, *LibCallI;
  654. std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
  655. getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
  656. Builder.CreateBr(ContBB);
  657. // Finally continue execution by phi-ing together the different
  658. // computation paths.
  659. CGF.EmitBlock(ContBB);
  660. llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
  661. RealPHI->addIncoming(ResR, OrigBB);
  662. RealPHI->addIncoming(ResR, INaNBB);
  663. RealPHI->addIncoming(LibCallR, LibCallBB);
  664. llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
  665. ImagPHI->addIncoming(ResI, OrigBB);
  666. ImagPHI->addIncoming(ResI, INaNBB);
  667. ImagPHI->addIncoming(LibCallI, LibCallBB);
  668. return ComplexPairTy(RealPHI, ImagPHI);
  669. }
  670. assert((Op.LHS.second || Op.RHS.second) &&
  671. "At least one operand must be complex!");
  672. // If either of the operands is a real rather than a complex, the
  673. // imaginary component is ignored when computing the real component of the
  674. // result.
  675. ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
  676. ResI = Op.LHS.second
  677. ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
  678. : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
  679. } else {
  680. assert(Op.LHS.second && Op.RHS.second &&
  681. "Both operands of integer complex operators must be complex!");
  682. Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
  683. Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
  684. ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
  685. Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
  686. Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
  687. ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
  688. }
  689. return ComplexPairTy(ResR, ResI);
  690. }
  691. // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
  692. // typed values.
  693. ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
  694. llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
  695. llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
  696. llvm::Value *DSTr, *DSTi;
  697. if (LHSr->getType()->isFloatingPointTy()) {
  698. // If we have a complex operand on the RHS and FastMath is not allowed, we
  699. // delegate to a libcall to handle all of the complexities and minimize
  700. // underflow/overflow cases. When FastMath is allowed we construct the
  701. // divide inline using the same algorithm as for integer operands.
  702. //
  703. // FIXME: We would be able to avoid the libcall in many places if we
  704. // supported imaginary types in addition to complex types.
  705. if (RHSi && !CGF.getLangOpts().FastMath) {
  706. BinOpInfo LibCallOp = Op;
  707. // If LHS was a real, supply a null imaginary part.
  708. if (!LHSi)
  709. LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
  710. switch (LHSr->getType()->getTypeID()) {
  711. default:
  712. llvm_unreachable("Unsupported floating point type!");
  713. case llvm::Type::HalfTyID:
  714. return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
  715. case llvm::Type::FloatTyID:
  716. return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
  717. case llvm::Type::DoubleTyID:
  718. return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
  719. case llvm::Type::PPC_FP128TyID:
  720. return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
  721. case llvm::Type::X86_FP80TyID:
  722. return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
  723. case llvm::Type::FP128TyID:
  724. return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
  725. }
  726. } else if (RHSi) {
  727. if (!LHSi)
  728. LHSi = llvm::Constant::getNullValue(RHSi->getType());
  729. // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
  730. llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
  731. llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
  732. llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
  733. llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
  734. llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
  735. llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
  736. llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
  737. llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
  738. llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
  739. DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
  740. DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
  741. } else {
  742. assert(LHSi && "Can have at most one non-complex operand!");
  743. DSTr = Builder.CreateFDiv(LHSr, RHSr);
  744. DSTi = Builder.CreateFDiv(LHSi, RHSr);
  745. }
  746. } else {
  747. assert(Op.LHS.second && Op.RHS.second &&
  748. "Both operands of integer complex operators must be complex!");
  749. // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
  750. llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
  751. llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
  752. llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
  753. llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
  754. llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
  755. llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
  756. llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
  757. llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
  758. llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
  759. if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
  760. DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
  761. DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
  762. } else {
  763. DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
  764. DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
  765. }
  766. }
  767. return ComplexPairTy(DSTr, DSTi);
  768. }
  769. ComplexExprEmitter::BinOpInfo
  770. ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
  771. TestAndClearIgnoreReal();
  772. TestAndClearIgnoreImag();
  773. BinOpInfo Ops;
  774. if (E->getLHS()->getType()->isRealFloatingType())
  775. Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
  776. else
  777. Ops.LHS = Visit(E->getLHS());
  778. if (E->getRHS()->getType()->isRealFloatingType())
  779. Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
  780. else
  781. Ops.RHS = Visit(E->getRHS());
  782. Ops.Ty = E->getType();
  783. return Ops;
  784. }
  785. LValue ComplexExprEmitter::
  786. EmitCompoundAssignLValue(const CompoundAssignOperator *E,
  787. ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
  788. RValue &Val) {
  789. TestAndClearIgnoreReal();
  790. TestAndClearIgnoreImag();
  791. QualType LHSTy = E->getLHS()->getType();
  792. if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
  793. LHSTy = AT->getValueType();
  794. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
  795. BinOpInfo OpInfo;
  796. // Load the RHS and LHS operands.
  797. // __block variables need to have the rhs evaluated first, plus this should
  798. // improve codegen a little.
  799. OpInfo.Ty = E->getComputationResultType();
  800. QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
  801. // The RHS should have been converted to the computation type.
  802. if (E->getRHS()->getType()->isRealFloatingType()) {
  803. assert(
  804. CGF.getContext()
  805. .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
  806. OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
  807. } else {
  808. assert(CGF.getContext()
  809. .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
  810. OpInfo.RHS = Visit(E->getRHS());
  811. }
  812. LValue LHS = CGF.EmitLValue(E->getLHS());
  813. // Load from the l-value and convert it.
  814. SourceLocation Loc = E->getExprLoc();
  815. if (LHSTy->isAnyComplexType()) {
  816. ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
  817. OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
  818. } else {
  819. llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
  820. // For floating point real operands we can directly pass the scalar form
  821. // to the binary operator emission and potentially get more efficient code.
  822. if (LHSTy->isRealFloatingType()) {
  823. if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
  824. LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
  825. OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
  826. } else {
  827. OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
  828. }
  829. }
  830. // Expand the binary operator.
  831. ComplexPairTy Result = (this->*Func)(OpInfo);
  832. // Truncate the result and store it into the LHS lvalue.
  833. if (LHSTy->isAnyComplexType()) {
  834. ComplexPairTy ResVal =
  835. EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
  836. EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
  837. Val = RValue::getComplex(ResVal);
  838. } else {
  839. llvm::Value *ResVal =
  840. CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
  841. CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
  842. Val = RValue::get(ResVal);
  843. }
  844. return LHS;
  845. }
  846. // Compound assignments.
  847. ComplexPairTy ComplexExprEmitter::
  848. EmitCompoundAssign(const CompoundAssignOperator *E,
  849. ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
  850. RValue Val;
  851. LValue LV = EmitCompoundAssignLValue(E, Func, Val);
  852. // The result of an assignment in C is the assigned r-value.
  853. if (!CGF.getLangOpts().CPlusPlus)
  854. return Val.getComplexVal();
  855. // If the lvalue is non-volatile, return the computed value of the assignment.
  856. if (!LV.isVolatileQualified())
  857. return Val.getComplexVal();
  858. return EmitLoadOfLValue(LV, E->getExprLoc());
  859. }
  860. LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
  861. ComplexPairTy &Val) {
  862. assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
  863. E->getRHS()->getType()) &&
  864. "Invalid assignment");
  865. TestAndClearIgnoreReal();
  866. TestAndClearIgnoreImag();
  867. // Emit the RHS. __block variables need the RHS evaluated first.
  868. Val = Visit(E->getRHS());
  869. // Compute the address to store into.
  870. LValue LHS = CGF.EmitLValue(E->getLHS());
  871. // Store the result value into the LHS lvalue.
  872. EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
  873. return LHS;
  874. }
  875. ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  876. ComplexPairTy Val;
  877. LValue LV = EmitBinAssignLValue(E, Val);
  878. // The result of an assignment in C is the assigned r-value.
  879. if (!CGF.getLangOpts().CPlusPlus)
  880. return Val;
  881. // If the lvalue is non-volatile, return the computed value of the assignment.
  882. if (!LV.isVolatileQualified())
  883. return Val;
  884. return EmitLoadOfLValue(LV, E->getExprLoc());
  885. }
  886. ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
  887. CGF.EmitIgnoredExpr(E->getLHS());
  888. return Visit(E->getRHS());
  889. }
  890. ComplexPairTy ComplexExprEmitter::
  891. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  892. TestAndClearIgnoreReal();
  893. TestAndClearIgnoreImag();
  894. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  895. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  896. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  897. // Bind the common expression if necessary.
  898. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  899. CodeGenFunction::ConditionalEvaluation eval(CGF);
  900. CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
  901. CGF.getProfileCount(E));
  902. eval.begin(CGF);
  903. CGF.EmitBlock(LHSBlock);
  904. CGF.incrementProfileCounter(E);
  905. ComplexPairTy LHS = Visit(E->getTrueExpr());
  906. LHSBlock = Builder.GetInsertBlock();
  907. CGF.EmitBranch(ContBlock);
  908. eval.end(CGF);
  909. eval.begin(CGF);
  910. CGF.EmitBlock(RHSBlock);
  911. ComplexPairTy RHS = Visit(E->getFalseExpr());
  912. RHSBlock = Builder.GetInsertBlock();
  913. CGF.EmitBlock(ContBlock);
  914. eval.end(CGF);
  915. // Create a PHI node for the real part.
  916. llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
  917. RealPN->addIncoming(LHS.first, LHSBlock);
  918. RealPN->addIncoming(RHS.first, RHSBlock);
  919. // Create a PHI node for the imaginary part.
  920. llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
  921. ImagPN->addIncoming(LHS.second, LHSBlock);
  922. ImagPN->addIncoming(RHS.second, RHSBlock);
  923. return ComplexPairTy(RealPN, ImagPN);
  924. }
  925. ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
  926. return Visit(E->getChosenSubExpr());
  927. }
  928. ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
  929. bool Ignore = TestAndClearIgnoreReal();
  930. (void)Ignore;
  931. assert (Ignore == false && "init list ignored");
  932. Ignore = TestAndClearIgnoreImag();
  933. (void)Ignore;
  934. assert (Ignore == false && "init list ignored");
  935. if (E->getNumInits() == 2) {
  936. llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
  937. llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
  938. return ComplexPairTy(Real, Imag);
  939. } else if (E->getNumInits() == 1) {
  940. return Visit(E->getInit(0));
  941. }
  942. // Empty init list initializes to null
  943. assert(E->getNumInits() == 0 && "Unexpected number of inits");
  944. QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
  945. llvm::Type* LTy = CGF.ConvertType(Ty);
  946. llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
  947. return ComplexPairTy(zeroConstant, zeroConstant);
  948. }
  949. ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
  950. Address ArgValue = Address::invalid();
  951. Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
  952. if (!ArgPtr.isValid()) {
  953. CGF.ErrorUnsupported(E, "complex va_arg expression");
  954. llvm::Type *EltTy =
  955. CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
  956. llvm::Value *U = llvm::UndefValue::get(EltTy);
  957. return ComplexPairTy(U, U);
  958. }
  959. return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
  960. E->getExprLoc());
  961. }
  962. //===----------------------------------------------------------------------===//
  963. // Entry Point into this File
  964. //===----------------------------------------------------------------------===//
  965. /// EmitComplexExpr - Emit the computation of the specified expression of
  966. /// complex type, ignoring the result.
  967. ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E, bool IgnoreReal,
  968. bool IgnoreImag) {
  969. assert(E && getComplexType(E->getType()) &&
  970. "Invalid complex expression to emit");
  971. return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
  972. .Visit(const_cast<Expr *>(E));
  973. }
  974. void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,
  975. bool isInit) {
  976. assert(E && getComplexType(E->getType()) &&
  977. "Invalid complex expression to emit");
  978. ComplexExprEmitter Emitter(*this);
  979. ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
  980. Emitter.EmitStoreOfComplex(Val, dest, isInit);
  981. }
  982. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  983. void CodeGenFunction::EmitStoreOfComplex(ComplexPairTy V, LValue dest,
  984. bool isInit) {
  985. ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
  986. }
  987. /// EmitLoadOfComplex - Load a complex number from the specified address.
  988. ComplexPairTy CodeGenFunction::EmitLoadOfComplex(LValue src,
  989. SourceLocation loc) {
  990. return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
  991. }
  992. LValue CodeGenFunction::EmitComplexAssignmentLValue(const BinaryOperator *E) {
  993. assert(E->getOpcode() == BO_Assign);
  994. ComplexPairTy Val; // ignored
  995. LValue LVal = ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
  996. if (getLangOpts().OpenMP)
  997. CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
  998. E->getLHS());
  999. return LVal;
  1000. }
  1001. typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
  1002. const ComplexExprEmitter::BinOpInfo &);
  1003. static CompoundFunc getComplexOp(BinaryOperatorKind Op) {
  1004. switch (Op) {
  1005. case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
  1006. case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
  1007. case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
  1008. case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
  1009. default:
  1010. llvm_unreachable("unexpected complex compound assignment");
  1011. }
  1012. }
  1013. LValue CodeGenFunction::
  1014. EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E) {
  1015. CompoundFunc Op = getComplexOp(E->getOpcode());
  1016. RValue Val;
  1017. return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
  1018. }
  1019. LValue CodeGenFunction::
  1020. EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  1021. llvm::Value *&Result) {
  1022. CompoundFunc Op = getComplexOp(E->getOpcode());
  1023. RValue Val;
  1024. LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
  1025. Result = Val.getScalarVal();
  1026. return Ret;
  1027. }