CGExprScalar.cpp revision 9b2dc287177394a8f73833e2ad4f7ca8cd6f22bb
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/Support/Compiler.h"
22#include <cstdarg>
23
24using namespace clang;
25using namespace CodeGen;
26using llvm::Value;
27
28//===----------------------------------------------------------------------===//
29//                         Scalar Expression Emitter
30//===----------------------------------------------------------------------===//
31
32struct BinOpInfo {
33  Value *LHS;
34  Value *RHS;
35  QualType Ty;  // Computation Type.
36  const BinaryOperator *E;
37};
38
39namespace {
40class VISIBILITY_HIDDEN ScalarExprEmitter
41  : public StmtVisitor<ScalarExprEmitter, Value*> {
42  CodeGenFunction &CGF;
43  llvm::LLVMFoldingBuilder &Builder;
44  CGObjCRuntime *Runtime;
45
46
47public:
48
49  ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
50    Builder(CGF.Builder),
51    Runtime(CGF.CGM.getObjCRuntime()) {
52  }
53
54  //===--------------------------------------------------------------------===//
55  //                               Utilities
56  //===--------------------------------------------------------------------===//
57
58  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
59  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
60
61  Value *EmitLoadOfLValue(LValue LV, QualType T) {
62    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
63  }
64
65  /// EmitLoadOfLValue - Given an expression with complex type that represents a
66  /// value l-value, this method emits the address of the l-value, then loads
67  /// and returns the result.
68  Value *EmitLoadOfLValue(const Expr *E) {
69    // FIXME: Volatile
70    return EmitLoadOfLValue(EmitLValue(E), E->getType());
71  }
72
73  /// EmitConversionToBool - Convert the specified expression value to a
74  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
75  Value *EmitConversionToBool(Value *Src, QualType DstTy);
76
77  /// EmitScalarConversion - Emit a conversion from the specified type to the
78  /// specified destination type, both of which are LLVM scalar types.
79  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
80
81  /// EmitComplexToScalarConversion - Emit a conversion from the specified
82  /// complex type to the specified destination type, where the destination
83  /// type is an LLVM scalar type.
84  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
85                                       QualType SrcTy, QualType DstTy);
86
87  //===--------------------------------------------------------------------===//
88  //                            Visitor Methods
89  //===--------------------------------------------------------------------===//
90
91  Value *VisitStmt(Stmt *S) {
92    S->dump(CGF.getContext().getSourceManager());
93    assert(0 && "Stmt can't have complex result type!");
94    return 0;
95  }
96  Value *VisitExpr(Expr *S);
97  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
98
99  // Leaves.
100  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
101    return llvm::ConstantInt::get(E->getValue());
102  }
103  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
104    return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
105  }
106  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
107    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
108  }
109  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
110    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111  }
112  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
113    return llvm::ConstantInt::get(ConvertType(E->getType()),
114                                  CGF.getContext().typesAreCompatible(
115                                    E->getArgType1(), E->getArgType2()));
116  }
117  Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
118    return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
119  }
120
121  // l-values.
122  Value *VisitDeclRefExpr(DeclRefExpr *E) {
123    if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
124      return llvm::ConstantInt::get(EC->getInitVal());
125    return EmitLoadOfLValue(E);
126  }
127  Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
128  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { return EmitLoadOfLValue(E);}
129  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
130  Value *VisitMemberExpr(Expr *E)           { return EmitLoadOfLValue(E); }
131  Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
132  Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
133  Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
134
135  Value *VisitInitListExpr(InitListExpr *E) {
136    unsigned NumInitElements = E->getNumInits();
137
138    const llvm::VectorType *VType =
139      dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
140
141    // We have a scalar in braces. Just use the first element.
142    if (!VType)
143      return Visit(E->getInit(0));
144
145    unsigned NumVectorElements = VType->getNumElements();
146    const llvm::Type *ElementType = VType->getElementType();
147
148    // Emit individual vector element stores.
149    llvm::Value *V = llvm::UndefValue::get(VType);
150
151    // Emit initializers
152    unsigned i;
153    for (i = 0; i < NumInitElements; ++i) {
154      Value *NewV = Visit(E->getInit(i));
155      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
156      V = Builder.CreateInsertElement(V, NewV, Idx);
157    }
158
159    // Emit remaining default initializers
160    for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
161      Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
162      llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
163      V = Builder.CreateInsertElement(V, NewV, Idx);
164    }
165
166    return V;
167  }
168
169  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
170    return Visit(E->getInitializer());
171  }
172
173  Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
174  Value *VisitCastExpr(const CastExpr *E) {
175    return EmitCastExpr(E->getSubExpr(), E->getType());
176  }
177  Value *EmitCastExpr(const Expr *E, QualType T);
178
179  Value *VisitCallExpr(const CallExpr *E) {
180    return CGF.EmitCallExpr(E).getScalarVal();
181  }
182
183  Value *VisitStmtExpr(const StmtExpr *E);
184
185  // Unary Operators.
186  Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
187  Value *VisitUnaryPostDec(const UnaryOperator *E) {
188    return VisitPrePostIncDec(E, false, false);
189  }
190  Value *VisitUnaryPostInc(const UnaryOperator *E) {
191    return VisitPrePostIncDec(E, true, false);
192  }
193  Value *VisitUnaryPreDec(const UnaryOperator *E) {
194    return VisitPrePostIncDec(E, false, true);
195  }
196  Value *VisitUnaryPreInc(const UnaryOperator *E) {
197    return VisitPrePostIncDec(E, true, true);
198  }
199  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
200    return EmitLValue(E->getSubExpr()).getAddress();
201  }
202  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
203  Value *VisitUnaryPlus(const UnaryOperator *E) {
204    return Visit(E->getSubExpr());
205  }
206  Value *VisitUnaryMinus    (const UnaryOperator *E);
207  Value *VisitUnaryNot      (const UnaryOperator *E);
208  Value *VisitUnaryLNot     (const UnaryOperator *E);
209  Value *VisitUnarySizeOf   (const UnaryOperator *E) {
210    return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
211  }
212  Value *VisitUnaryAlignOf  (const UnaryOperator *E) {
213    return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
214  }
215  Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
216                         bool isSizeOf);
217  Value *VisitUnaryReal     (const UnaryOperator *E);
218  Value *VisitUnaryImag     (const UnaryOperator *E);
219  Value *VisitUnaryExtension(const UnaryOperator *E) {
220    return Visit(E->getSubExpr());
221  }
222  Value *VisitUnaryOffsetOf(const UnaryOperator *E);
223
224  // Binary Operators.
225  Value *EmitMul(const BinOpInfo &Ops) {
226    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
227  }
228  Value *EmitDiv(const BinOpInfo &Ops);
229  Value *EmitRem(const BinOpInfo &Ops);
230  Value *EmitAdd(const BinOpInfo &Ops);
231  Value *EmitSub(const BinOpInfo &Ops);
232  Value *EmitShl(const BinOpInfo &Ops);
233  Value *EmitShr(const BinOpInfo &Ops);
234  Value *EmitAnd(const BinOpInfo &Ops) {
235    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
236  }
237  Value *EmitXor(const BinOpInfo &Ops) {
238    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
239  }
240  Value *EmitOr (const BinOpInfo &Ops) {
241    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
242  }
243
244  BinOpInfo EmitBinOps(const BinaryOperator *E);
245  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
246                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
247
248  // Binary operators and binary compound assignment operators.
249#define HANDLEBINOP(OP) \
250  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
251    return Emit ## OP(EmitBinOps(E));                                      \
252  }                                                                        \
253  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
254    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
255  }
256  HANDLEBINOP(Mul);
257  HANDLEBINOP(Div);
258  HANDLEBINOP(Rem);
259  HANDLEBINOP(Add);
260  //         (Sub) - Sub is handled specially below for ptr-ptr subtract.
261  HANDLEBINOP(Shl);
262  HANDLEBINOP(Shr);
263  HANDLEBINOP(And);
264  HANDLEBINOP(Xor);
265  HANDLEBINOP(Or);
266#undef HANDLEBINOP
267  Value *VisitBinSub(const BinaryOperator *E);
268  Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
269    return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
270  }
271
272  // Comparisons.
273  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
274                     unsigned SICmpOpc, unsigned FCmpOpc);
275#define VISITCOMP(CODE, UI, SI, FP) \
276    Value *VisitBin##CODE(const BinaryOperator *E) { \
277      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
278                         llvm::FCmpInst::FP); }
279  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
280  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
281  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
282  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
283  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
284  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
285#undef VISITCOMP
286
287  Value *VisitBinAssign     (const BinaryOperator *E);
288
289  Value *VisitBinLAnd       (const BinaryOperator *E);
290  Value *VisitBinLOr        (const BinaryOperator *E);
291  Value *VisitBinComma      (const BinaryOperator *E);
292
293  // Other Operators.
294  Value *VisitConditionalOperator(const ConditionalOperator *CO);
295  Value *VisitChooseExpr(ChooseExpr *CE);
296  Value *VisitOverloadExpr(OverloadExpr *OE);
297  Value *VisitVAArgExpr(VAArgExpr *VE);
298  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
299    return CGF.EmitObjCStringLiteral(E);
300  }
301  Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
302};
303}  // end anonymous namespace.
304
305//===----------------------------------------------------------------------===//
306//                                Utilities
307//===----------------------------------------------------------------------===//
308
309/// EmitConversionToBool - Convert the specified expression value to a
310/// boolean (i1) truth value.  This is equivalent to "Val != 0".
311Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
312  assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
313
314  if (SrcType->isRealFloatingType()) {
315    // Compare against 0.0 for fp scalars.
316    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
317    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
318  }
319
320  assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
321         "Unknown scalar type to convert");
322
323  // Because of the type rules of C, we often end up computing a logical value,
324  // then zero extending it to int, then wanting it as a logical value again.
325  // Optimize this common case.
326  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
327    if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
328      Value *Result = ZI->getOperand(0);
329      // If there aren't any more uses, zap the instruction to save space.
330      // Note that there can be more uses, for example if this
331      // is the result of an assignment.
332      if (ZI->use_empty())
333        ZI->eraseFromParent();
334      return Result;
335    }
336  }
337
338  // Compare against an integer or pointer null.
339  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
340  return Builder.CreateICmpNE(Src, Zero, "tobool");
341}
342
343/// EmitScalarConversion - Emit a conversion from the specified type to the
344/// specified destination type, both of which are LLVM scalar types.
345Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
346                                               QualType DstType) {
347  SrcType = SrcType.getCanonicalType();
348  DstType = DstType.getCanonicalType();
349  if (SrcType == DstType) return Src;
350
351  if (DstType->isVoidType()) return 0;
352
353  // Handle conversions to bool first, they are special: comparisons against 0.
354  if (DstType->isBooleanType())
355    return EmitConversionToBool(Src, SrcType);
356
357  const llvm::Type *DstTy = ConvertType(DstType);
358
359  // Ignore conversions like int -> uint.
360  if (Src->getType() == DstTy)
361    return Src;
362
363  // Handle pointer conversions next: pointers can only be converted to/from
364  // other pointers and integers.
365  if (isa<PointerType>(DstType)) {
366    // The source value may be an integer, or a pointer.
367    if (isa<llvm::PointerType>(Src->getType()))
368      return Builder.CreateBitCast(Src, DstTy, "conv");
369    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
370    return Builder.CreateIntToPtr(Src, DstTy, "conv");
371  }
372
373  if (isa<PointerType>(SrcType)) {
374    // Must be an ptr to int cast.
375    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
376    return Builder.CreatePtrToInt(Src, DstTy, "conv");
377  }
378
379  // A scalar source can be splatted to an OCU vector of the same element type
380  if (DstType->isOCUVectorType() && !isa<VectorType>(SrcType) &&
381      cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
382    return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
383                          true);
384
385  // Allow bitcast from vector to integer/fp of the same size.
386  if (isa<llvm::VectorType>(Src->getType()) ||
387      isa<llvm::VectorType>(DstTy))
388    return Builder.CreateBitCast(Src, DstTy, "conv");
389
390  // Finally, we have the arithmetic types: real int/float.
391  if (isa<llvm::IntegerType>(Src->getType())) {
392    bool InputSigned = SrcType->isSignedIntegerType();
393    if (isa<llvm::IntegerType>(DstTy))
394      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
395    else if (InputSigned)
396      return Builder.CreateSIToFP(Src, DstTy, "conv");
397    else
398      return Builder.CreateUIToFP(Src, DstTy, "conv");
399  }
400
401  assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
402  if (isa<llvm::IntegerType>(DstTy)) {
403    if (DstType->isSignedIntegerType())
404      return Builder.CreateFPToSI(Src, DstTy, "conv");
405    else
406      return Builder.CreateFPToUI(Src, DstTy, "conv");
407  }
408
409  assert(DstTy->isFloatingPoint() && "Unknown real conversion");
410  if (DstTy->getTypeID() < Src->getType()->getTypeID())
411    return Builder.CreateFPTrunc(Src, DstTy, "conv");
412  else
413    return Builder.CreateFPExt(Src, DstTy, "conv");
414}
415
416/// EmitComplexToScalarConversion - Emit a conversion from the specified
417/// complex type to the specified destination type, where the destination
418/// type is an LLVM scalar type.
419Value *ScalarExprEmitter::
420EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
421                              QualType SrcTy, QualType DstTy) {
422  // Get the source element type.
423  SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
424
425  // Handle conversions to bool first, they are special: comparisons against 0.
426  if (DstTy->isBooleanType()) {
427    //  Complex != 0  -> (Real != 0) | (Imag != 0)
428    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
429    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
430    return Builder.CreateOr(Src.first, Src.second, "tobool");
431  }
432
433  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
434  // the imaginary part of the complex value is discarded and the value of the
435  // real part is converted according to the conversion rules for the
436  // corresponding real type.
437  return EmitScalarConversion(Src.first, SrcTy, DstTy);
438}
439
440
441//===----------------------------------------------------------------------===//
442//                            Visitor Methods
443//===----------------------------------------------------------------------===//
444
445Value *ScalarExprEmitter::VisitExpr(Expr *E) {
446  CGF.WarnUnsupported(E, "scalar expression");
447  if (E->getType()->isVoidType())
448    return 0;
449  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
450}
451
452Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
453  // Only the lookup mechanism and first two arguments of the method
454  // implementation vary between runtimes.  We can get the receiver and
455  // arguments in generic code.
456
457  // Find the receiver
458  llvm::Value *Receiver = CGF.EmitScalarExpr(E->getReceiver());
459
460  // Process the arguments
461  unsigned ArgC = E->getNumArgs();
462  llvm::SmallVector<llvm::Value*, 16> Args;
463  for (unsigned i = 0; i != ArgC; ++i) {
464    Expr *ArgExpr = E->getArg(i);
465    QualType ArgTy = ArgExpr->getType();
466    if (!CGF.hasAggregateLLVMType(ArgTy)) {
467      // Scalar argument is passed by-value.
468      Args.push_back(CGF.EmitScalarExpr(ArgExpr));
469    } else if (ArgTy->isAnyComplexType()) {
470      // Make a temporary alloca to pass the argument.
471      llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
472      CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
473      Args.push_back(DestMem);
474    } else {
475      llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
476      CGF.EmitAggExpr(ArgExpr, DestMem, false);
477      Args.push_back(DestMem);
478    }
479  }
480
481  // Get the selector string
482  std::string SelStr = E->getSelector().getName();
483  llvm::Constant *Selector = CGF.CGM.GetAddrOfConstantString(SelStr);
484
485  llvm::Value *SelPtr = Builder.CreateStructGEP(Selector, 0);
486  return Runtime->generateMessageSend(Builder, ConvertType(E->getType()),
487                                      CGF.LoadObjCSelf(),
488                                      Receiver, SelPtr,
489                                      &Args[0], Args.size());
490}
491
492Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
493  // Emit subscript expressions in rvalue context's.  For most cases, this just
494  // loads the lvalue formed by the subscript expr.  However, we have to be
495  // careful, because the base of a vector subscript is occasionally an rvalue,
496  // so we can't get it as an lvalue.
497  if (!E->getBase()->getType()->isVectorType())
498    return EmitLoadOfLValue(E);
499
500  // Handle the vector case.  The base must be a vector, the index must be an
501  // integer value.
502  Value *Base = Visit(E->getBase());
503  Value *Idx  = Visit(E->getIdx());
504
505  // FIXME: Convert Idx to i32 type.
506  return Builder.CreateExtractElement(Base, Idx, "vecext");
507}
508
509/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
510/// also handle things like function to pointer-to-function decay, and array to
511/// pointer decay.
512Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
513  const Expr *Op = E->getSubExpr();
514
515  // If this is due to array->pointer conversion, emit the array expression as
516  // an l-value.
517  if (Op->getType()->isArrayType()) {
518    // FIXME: For now we assume that all source arrays map to LLVM arrays.  This
519    // will not true when we add support for VLAs.
520    Value *V = EmitLValue(Op).getAddress();  // Bitfields can't be arrays.
521
522    assert(isa<llvm::PointerType>(V->getType()) &&
523           isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
524                                ->getElementType()) &&
525           "Doesn't support VLAs yet!");
526    V = Builder.CreateStructGEP(V, 0, "arraydecay");
527
528    // The resultant pointer type can be implicitly casted to other pointer
529    // types as well, for example void*.
530    const llvm::Type *DestPTy = ConvertType(E->getType());
531    assert(isa<llvm::PointerType>(DestPTy) &&
532           "Only expect implicit cast to pointer");
533    if (V->getType() != DestPTy)
534      V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
535    return V;
536
537  } else if (E->getType()->isReferenceType()) {
538    assert(cast<ReferenceType>(E->getType().getCanonicalType())->
539           getPointeeType() ==
540           Op->getType().getCanonicalType() && "Incompatible types!");
541
542    return EmitLValue(Op).getAddress();
543  }
544
545  return EmitCastExpr(Op, E->getType());
546}
547
548
549// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
550// have to handle a more broad range of conversions than explicit casts, as they
551// handle things like function to ptr-to-function decay etc.
552Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
553  // Handle cases where the source is an non-complex type.
554
555  if (!CGF.hasAggregateLLVMType(E->getType())) {
556    Value *Src = Visit(const_cast<Expr*>(E));
557
558    // Use EmitScalarConversion to perform the conversion.
559    return EmitScalarConversion(Src, E->getType(), DestTy);
560  }
561
562  if (E->getType()->isAnyComplexType()) {
563    // Handle cases where the source is a complex type.
564    return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
565                                         DestTy);
566  }
567
568  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
569  // evaluate the result and return.
570  CGF.EmitAggExpr(E, 0, false);
571  return 0;
572}
573
574Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
575  return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
576}
577
578
579//===----------------------------------------------------------------------===//
580//                             Unary Operators
581//===----------------------------------------------------------------------===//
582
583Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
584                                             bool isInc, bool isPre) {
585  LValue LV = EmitLValue(E->getSubExpr());
586  // FIXME: Handle volatile!
587  Value *InVal = CGF.EmitLoadOfLValue(LV, // false
588                                     E->getSubExpr()->getType()).getScalarVal();
589
590  int AmountVal = isInc ? 1 : -1;
591
592  Value *NextVal;
593  if (isa<llvm::PointerType>(InVal->getType())) {
594    // FIXME: This isn't right for VLAs.
595    NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
596    NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
597  } else {
598    // Add the inc/dec to the real part.
599    if (isa<llvm::IntegerType>(InVal->getType()))
600      NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
601    else if (InVal->getType() == llvm::Type::FloatTy)
602      // FIXME: Handle long double.
603      NextVal =
604        llvm::ConstantFP::get(InVal->getType(),
605                              llvm::APFloat(static_cast<float>(AmountVal)));
606    else {
607      // FIXME: Handle long double.
608      assert(InVal->getType() == llvm::Type::DoubleTy);
609      NextVal =
610        llvm::ConstantFP::get(InVal->getType(),
611                              llvm::APFloat(static_cast<double>(AmountVal)));
612    }
613    NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
614  }
615
616  // Store the updated result through the lvalue.
617  CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
618                             E->getSubExpr()->getType());
619
620  // If this is a postinc, return the value read from memory, otherwise use the
621  // updated value.
622  return isPre ? NextVal : InVal;
623}
624
625
626Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
627  Value *Op = Visit(E->getSubExpr());
628  return Builder.CreateNeg(Op, "neg");
629}
630
631Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
632  Value *Op = Visit(E->getSubExpr());
633  return Builder.CreateNot(Op, "neg");
634}
635
636Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
637  // Compare operand to zero.
638  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
639
640  // Invert value.
641  // TODO: Could dynamically modify easy computations here.  For example, if
642  // the operand is an icmp ne, turn into icmp eq.
643  BoolVal = Builder.CreateNot(BoolVal, "lnot");
644
645  // ZExt result to int.
646  return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
647}
648
649/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
650/// an integer (RetType).
651Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
652                                          QualType RetType,bool isSizeOf){
653  assert(RetType->isIntegerType() && "Result type must be an integer!");
654  uint32_t ResultWidth =
655    static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType));
656
657  // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
658  if (TypeToSize->isVoidType())
659    return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
660
661  /// FIXME: This doesn't handle VLAs yet!
662  std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize);
663
664  uint64_t Val = isSizeOf ? Info.first : Info.second;
665  Val /= 8;  // Return size in bytes, not bits.
666
667  return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
668}
669
670Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
671  Expr *Op = E->getSubExpr();
672  if (Op->getType()->isAnyComplexType())
673    return CGF.EmitComplexExpr(Op).first;
674  return Visit(Op);
675}
676Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
677  Expr *Op = E->getSubExpr();
678  if (Op->getType()->isAnyComplexType())
679    return CGF.EmitComplexExpr(Op).second;
680
681  // __imag on a scalar returns zero.  Emit it the subexpr to ensure side
682  // effects are evaluated.
683  CGF.EmitScalarExpr(Op);
684  return llvm::Constant::getNullValue(ConvertType(E->getType()));
685}
686
687Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
688{
689  int64_t Val = E->evaluateOffsetOf(CGF.getContext());
690
691  assert(E->getType()->isIntegerType() && "Result type must be an integer!");
692
693  uint32_t ResultWidth =
694    static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType()));
695  return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
696}
697
698//===----------------------------------------------------------------------===//
699//                           Binary Operators
700//===----------------------------------------------------------------------===//
701
702BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
703  BinOpInfo Result;
704  Result.LHS = Visit(E->getLHS());
705  Result.RHS = Visit(E->getRHS());
706  Result.Ty  = E->getType();
707  Result.E = E;
708  return Result;
709}
710
711Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
712                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
713  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
714
715  BinOpInfo OpInfo;
716
717  // Load the LHS and RHS operands.
718  LValue LHSLV = EmitLValue(E->getLHS());
719  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
720
721  // Determine the computation type.  If the RHS is complex, then this is one of
722  // the add/sub/mul/div operators.  All of these operators can be computed in
723  // with just their real component even though the computation domain really is
724  // complex.
725  QualType ComputeType = E->getComputationType();
726
727  // If the computation type is complex, then the RHS is complex.  Emit the RHS.
728  if (const ComplexType *CT = ComputeType->getAsComplexType()) {
729    ComputeType = CT->getElementType();
730
731    // Emit the RHS, only keeping the real component.
732    OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
733    RHSTy = RHSTy->getAsComplexType()->getElementType();
734  } else {
735    // Otherwise the RHS is a simple scalar value.
736    OpInfo.RHS = Visit(E->getRHS());
737  }
738
739  // Convert the LHS/RHS values to the computation type.
740  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
741
742  // Do not merge types for -= or += where the LHS is a pointer.
743  if (!(E->getOpcode() == BinaryOperator::SubAssign ||
744        E->getOpcode() == BinaryOperator::AddAssign) ||
745      !E->getLHS()->getType()->isPointerType()) {
746    OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
747  }
748  OpInfo.Ty = ComputeType;
749  OpInfo.E = E;
750
751  // Expand the binary operator.
752  Value *Result = (this->*Func)(OpInfo);
753
754  // Truncate the result back to the LHS type.
755  Result = EmitScalarConversion(Result, ComputeType, LHSTy);
756
757  // Store the result value into the LHS lvalue.
758  CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
759
760  return Result;
761}
762
763
764Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
765  if (Ops.LHS->getType()->isFPOrFPVector())
766    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
767  else if (Ops.Ty->isUnsignedIntegerType())
768    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
769  else
770    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
771}
772
773Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
774  // Rem in C can't be a floating point type: C99 6.5.5p2.
775  if (Ops.Ty->isUnsignedIntegerType())
776    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
777  else
778    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
779}
780
781
782Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
783  if (!Ops.Ty->isPointerType())
784    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
785
786  // FIXME: What about a pointer to a VLA?
787  Value *Ptr, *Idx;
788  Expr *IdxExp;
789  if (isa<llvm::PointerType>(Ops.LHS->getType())) {  // pointer + int
790    Ptr = Ops.LHS;
791    Idx = Ops.RHS;
792    IdxExp = Ops.E->getRHS();
793  } else {                                           // int + pointer
794    Ptr = Ops.RHS;
795    Idx = Ops.LHS;
796    IdxExp = Ops.E->getLHS();
797  }
798
799  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
800  if (Width < CGF.LLVMPointerWidth) {
801    // Zero or sign extend the pointer value based on whether the index is
802    // signed or not.
803    const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
804    if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
805      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
806    else
807      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
808  }
809
810  return Builder.CreateGEP(Ptr, Idx, "add.ptr");
811}
812
813Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
814  if (!isa<llvm::PointerType>(Ops.LHS->getType()))
815    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
816
817  // pointer - int
818  assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
819         "ptr-ptr shouldn't get here");
820  // FIXME: The pointer could point to a VLA.
821  Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
822
823  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
824  if (Width < CGF.LLVMPointerWidth) {
825    // Zero or sign extend the pointer value based on whether the index is
826    // signed or not.
827    const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
828    if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
829      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
830    else
831      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
832  }
833
834  return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
835}
836
837Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
838  // "X - Y" is different from "X -= Y" in one case: when Y is a pointer.  In
839  // the compound assignment case it is invalid, so just handle it here.
840  if (!E->getRHS()->getType()->isPointerType())
841    return EmitSub(EmitBinOps(E));
842
843  // pointer - pointer
844  Value *LHS = Visit(E->getLHS());
845  Value *RHS = Visit(E->getRHS());
846
847  const QualType LHSType = E->getLHS()->getType().getCanonicalType();
848  const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
849  uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
850
851  const llvm::Type *ResultType = ConvertType(E->getType());
852  LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
853  RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
854  Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
855
856  // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
857  // remainder.  As such, we handle common power-of-two cases here to generate
858  // better code.
859  if (llvm::isPowerOf2_64(ElementSize)) {
860    Value *ShAmt =
861    llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
862    return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
863  }
864
865  // Otherwise, do a full sdiv.
866  Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
867  return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
868}
869
870
871Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
872  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
873  // RHS to the same size as the LHS.
874  Value *RHS = Ops.RHS;
875  if (Ops.LHS->getType() != RHS->getType())
876    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
877
878  return Builder.CreateShl(Ops.LHS, RHS, "shl");
879}
880
881Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
882  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
883  // RHS to the same size as the LHS.
884  Value *RHS = Ops.RHS;
885  if (Ops.LHS->getType() != RHS->getType())
886    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
887
888  if (Ops.Ty->isUnsignedIntegerType())
889    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
890  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
891}
892
893Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
894                                      unsigned SICmpOpc, unsigned FCmpOpc) {
895  Value *Result;
896  QualType LHSTy = E->getLHS()->getType();
897  if (!LHSTy->isAnyComplexType()) {
898    Value *LHS = Visit(E->getLHS());
899    Value *RHS = Visit(E->getRHS());
900
901    if (LHS->getType()->isFloatingPoint()) {
902      Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
903                                  LHS, RHS, "cmp");
904    } else if (LHSTy->isUnsignedIntegerType()) {
905      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
906                                  LHS, RHS, "cmp");
907    } else {
908      // Signed integers and pointers.
909      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
910                                  LHS, RHS, "cmp");
911    }
912  } else {
913    // Complex Comparison: can only be an equality comparison.
914    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
915    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
916
917    QualType CETy =
918      cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
919
920    Value *ResultR, *ResultI;
921    if (CETy->isRealFloatingType()) {
922      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
923                                   LHS.first, RHS.first, "cmp.r");
924      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
925                                   LHS.second, RHS.second, "cmp.i");
926    } else {
927      // Complex comparisons can only be equality comparisons.  As such, signed
928      // and unsigned opcodes are the same.
929      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
930                                   LHS.first, RHS.first, "cmp.r");
931      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
932                                   LHS.second, RHS.second, "cmp.i");
933    }
934
935    if (E->getOpcode() == BinaryOperator::EQ) {
936      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
937    } else {
938      assert(E->getOpcode() == BinaryOperator::NE &&
939             "Complex comparison other than == or != ?");
940      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
941    }
942  }
943
944  // ZExt result to int.
945  return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
946}
947
948Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
949  LValue LHS = EmitLValue(E->getLHS());
950  Value *RHS = Visit(E->getRHS());
951
952  // Store the value into the LHS.
953  // FIXME: Volatility!
954  CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
955
956  // Return the RHS.
957  return RHS;
958}
959
960Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
961  Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
962
963  llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
964  llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
965
966  llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
967  Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
968
969  CGF.EmitBlock(RHSBlock);
970  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
971
972  // Reaquire the RHS block, as there may be subblocks inserted.
973  RHSBlock = Builder.GetInsertBlock();
974  CGF.EmitBlock(ContBlock);
975
976  // Create a PHI node.  If we just evaluted the LHS condition, the result is
977  // false.  If we evaluated both, the result is the RHS condition.
978  llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
979  PN->reserveOperandSpace(2);
980  PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
981  PN->addIncoming(RHSCond, RHSBlock);
982
983  // ZExt result to int.
984  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
985}
986
987Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
988  Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
989
990  llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
991  llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
992
993  llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
994  Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
995
996  CGF.EmitBlock(RHSBlock);
997  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
998
999  // Reaquire the RHS block, as there may be subblocks inserted.
1000  RHSBlock = Builder.GetInsertBlock();
1001  CGF.EmitBlock(ContBlock);
1002
1003  // Create a PHI node.  If we just evaluted the LHS condition, the result is
1004  // true.  If we evaluated both, the result is the RHS condition.
1005  llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1006  PN->reserveOperandSpace(2);
1007  PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1008  PN->addIncoming(RHSCond, RHSBlock);
1009
1010  // ZExt result to int.
1011  return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1012}
1013
1014Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1015  CGF.EmitStmt(E->getLHS());
1016  return Visit(E->getRHS());
1017}
1018
1019//===----------------------------------------------------------------------===//
1020//                             Other Operators
1021//===----------------------------------------------------------------------===//
1022
1023Value *ScalarExprEmitter::
1024VisitConditionalOperator(const ConditionalOperator *E) {
1025  llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1026  llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1027  llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1028
1029  // Evaluate the conditional, then convert it to bool.  We do this explicitly
1030  // because we need the unconverted value if this is a GNU ?: expression with
1031  // missing middle value.
1032  Value *CondVal = CGF.EmitScalarExpr(E->getCond());
1033  Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1034                                               CGF.getContext().BoolTy);
1035  Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1036
1037  CGF.EmitBlock(LHSBlock);
1038
1039  // Handle the GNU extension for missing LHS.
1040  Value *LHS;
1041  if (E->getLHS())
1042    LHS = Visit(E->getLHS());
1043  else    // Perform promotions, to handle cases like "short ?: int"
1044    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1045
1046  Builder.CreateBr(ContBlock);
1047  LHSBlock = Builder.GetInsertBlock();
1048
1049  CGF.EmitBlock(RHSBlock);
1050
1051  Value *RHS = Visit(E->getRHS());
1052  Builder.CreateBr(ContBlock);
1053  RHSBlock = Builder.GetInsertBlock();
1054
1055  CGF.EmitBlock(ContBlock);
1056
1057  if (!LHS) {
1058    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1059    return 0;
1060  }
1061
1062  // Create a PHI node for the real part.
1063  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1064  PN->reserveOperandSpace(2);
1065  PN->addIncoming(LHS, LHSBlock);
1066  PN->addIncoming(RHS, RHSBlock);
1067  return PN;
1068}
1069
1070Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1071  // Emit the LHS or RHS as appropriate.
1072  return
1073    Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
1074}
1075
1076Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
1077  return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1078                          E->getNumArgs(CGF.getContext())).getScalarVal();
1079}
1080
1081Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1082  llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1083
1084  llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1085  return V;
1086}
1087
1088Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1089  std::string str;
1090  llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1091  CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1092                                          EncodingRecordTypes);
1093
1094  llvm::Constant *C = llvm::ConstantArray::get(str);
1095  C = new llvm::GlobalVariable(C->getType(), true,
1096                               llvm::GlobalValue::InternalLinkage,
1097                               C, ".str", &CGF.CGM.getModule());
1098  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1099  llvm::Constant *Zeros[] = { Zero, Zero };
1100  C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1101
1102  return C;
1103}
1104
1105//===----------------------------------------------------------------------===//
1106//                         Entry Point into this File
1107//===----------------------------------------------------------------------===//
1108
1109/// EmitComplexExpr - Emit the computation of the specified expression of
1110/// complex type, ignoring the result.
1111Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1112  assert(E && !hasAggregateLLVMType(E->getType()) &&
1113         "Invalid scalar expression to emit");
1114
1115  return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1116}
1117
1118/// EmitScalarConversion - Emit a conversion from the specified type to the
1119/// specified destination type, both of which are LLVM scalar types.
1120Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1121                                             QualType DstTy) {
1122  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1123         "Invalid scalar expression to emit");
1124  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1125}
1126
1127/// EmitComplexToScalarConversion - Emit a conversion from the specified
1128/// complex type to the specified destination type, where the destination
1129/// type is an LLVM scalar type.
1130Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1131                                                      QualType SrcTy,
1132                                                      QualType DstTy) {
1133  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1134         "Invalid complex -> scalar conversion");
1135  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1136                                                                DstTy);
1137}
1138
1139Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1140  assert(V1->getType() == V2->getType() &&
1141         "Vector operands must be of the same type");
1142
1143  unsigned NumElements =
1144    cast<llvm::VectorType>(V1->getType())->getNumElements();
1145
1146  va_list va;
1147  va_start(va, V2);
1148
1149  llvm::SmallVector<llvm::Constant*, 16> Args;
1150
1151  for (unsigned i = 0; i < NumElements; i++) {
1152    int n = va_arg(va, int);
1153
1154    assert(n >= 0 && n < (int)NumElements * 2 &&
1155           "Vector shuffle index out of bounds!");
1156
1157    Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1158  }
1159
1160  const char *Name = va_arg(va, const char *);
1161  va_end(va);
1162
1163  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1164
1165  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1166}
1167
1168llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1169                                         unsigned NumVals, bool isSplat)
1170{
1171  llvm::Value *Vec
1172  = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1173
1174  for (unsigned i = 0, e = NumVals ; i != e; ++i) {
1175    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1176    llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1177    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1178  }
1179
1180  return Vec;
1181}
1182