CGExpr.cpp revision 0ee33cf81eb7e7e53a897efb772edf4d53af5bf1
1//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
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 as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "CGCall.h"
17#include "CGObjCRuntime.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "llvm/Target/TargetData.h"
21using namespace clang;
22using namespace CodeGen;
23
24//===--------------------------------------------------------------------===//
25//                        Miscellaneous Helper Methods
26//===--------------------------------------------------------------------===//
27
28/// CreateTempAlloca - This creates a alloca and inserts it into the entry
29/// block.
30llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
31                                                    const char *Name) {
32  if (!Builder.isNamePreserving())
33    Name = "";
34  return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35}
36
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
39llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
40  QualType BoolTy = getContext().BoolTy;
41  if (!E->getType()->isAnyComplexType())
42    return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
43
44  return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
45}
46
47/// EmitAnyExpr - Emit code to compute the specified expression which can have
48/// any type.  The result is returned as an RValue struct.  If this is an
49/// aggregate expression, the aggloc/agglocvolatile arguments indicate where the
50/// result should be returned.
51RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
52                                    bool IsAggLocVolatile, bool IgnoreResult,
53                                    bool IsInitializer) {
54  if (!hasAggregateLLVMType(E->getType()))
55    return RValue::get(EmitScalarExpr(E, IgnoreResult));
56  else if (E->getType()->isAnyComplexType())
57    return RValue::getComplex(EmitComplexExpr(E, false, false,
58                                              IgnoreResult, IgnoreResult));
59
60  EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer);
61  return RValue::getAggregate(AggLoc, IsAggLocVolatile);
62}
63
64/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
65/// always be accessible even if no aggregate location is provided.
66RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E,
67                                          bool IsAggLocVolatile,
68                                          bool IsInitializer) {
69  llvm::Value *AggLoc = 0;
70
71  if (hasAggregateLLVMType(E->getType()) &&
72      !E->getType()->isAnyComplexType())
73    AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp");
74  return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false,
75                     IsInitializer);
76}
77
78RValue CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E,
79                                                   QualType DestType,
80                                                   bool IsInitializer) {
81  RValue Val;
82  if (E->isLvalue(getContext()) == Expr::LV_Valid) {
83    // Emit the expr as an lvalue.
84    LValue LV = EmitLValue(E);
85    if (LV.isSimple())
86      return RValue::get(LV.getAddress());
87    Val = EmitLoadOfLValue(LV, E->getType());
88  } else {
89    // FIXME: Initializers don't work with casts yet. For example
90    // const A& a = B();
91    // if B inherits from A.
92    Val = EmitAnyExprToTemp(E, /*IsAggLocVolatile=*/false,
93                            IsInitializer);
94
95    if (IsInitializer) {
96      // We might have to destroy the temporary variable.
97      if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
98        if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
99          if (!ClassDecl->hasTrivialDestructor()) {
100            const CXXDestructorDecl *Dtor =
101              ClassDecl->getDestructor(getContext());
102
103            CleanupScope scope(*this);
104            EmitCXXDestructorCall(Dtor, Dtor_Complete, Val.getAggregateAddr());
105          }
106        }
107      }
108    }
109  }
110
111  if (Val.isAggregate()) {
112    Val = RValue::get(Val.getAggregateAddr());
113  } else {
114    // Create a temporary variable that we can bind the reference to.
115    llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()),
116                                         "reftmp");
117    if (Val.isScalar())
118      EmitStoreOfScalar(Val.getScalarVal(), Temp, false, E->getType());
119    else
120      StoreComplexToAddr(Val.getComplexVal(), Temp, false);
121    Val = RValue::get(Temp);
122  }
123
124  return Val;
125}
126
127
128/// getAccessedFieldNo - Given an encoded value and a result number, return the
129/// input field number being accessed.
130unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
131                                             const llvm::Constant *Elts) {
132  if (isa<llvm::ConstantAggregateZero>(Elts))
133    return 0;
134
135  return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
136}
137
138
139//===----------------------------------------------------------------------===//
140//                         LValue Expression Emission
141//===----------------------------------------------------------------------===//
142
143RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
144  if (Ty->isVoidType()) {
145    return RValue::get(0);
146  } else if (const ComplexType *CTy = Ty->getAsComplexType()) {
147    const llvm::Type *EltTy = ConvertType(CTy->getElementType());
148    llvm::Value *U = llvm::UndefValue::get(EltTy);
149    return RValue::getComplex(std::make_pair(U, U));
150  } else if (hasAggregateLLVMType(Ty)) {
151    const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty));
152    return RValue::getAggregate(llvm::UndefValue::get(LTy));
153  } else {
154    return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
155  }
156}
157
158RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
159                                              const char *Name) {
160  ErrorUnsupported(E, Name);
161  return GetUndefRValue(E->getType());
162}
163
164LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
165                                              const char *Name) {
166  ErrorUnsupported(E, Name);
167  llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
168  return LValue::MakeAddr(llvm::UndefValue::get(Ty),
169                          E->getType().getCVRQualifiers(),
170                          getContext().getObjCGCAttrKind(E->getType()),
171                          E->getType().getAddressSpace());
172}
173
174/// EmitLValue - Emit code to compute a designator that specifies the location
175/// of the expression.
176///
177/// This can return one of two things: a simple address or a bitfield reference.
178/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
179/// an LLVM pointer type.
180///
181/// If this returns a bitfield reference, nothing about the pointee type of the
182/// LLVM value is known: For example, it may not be a pointer to an integer.
183///
184/// If this returns a normal address, and if the lvalue's C type is fixed size,
185/// this method guarantees that the returned pointer type will point to an LLVM
186/// type of the same size of the lvalue's type.  If the lvalue has a variable
187/// length type, this is not possible.
188///
189LValue CodeGenFunction::EmitLValue(const Expr *E) {
190  switch (E->getStmtClass()) {
191  default: return EmitUnsupportedLValue(E, "l-value expression");
192
193  case Expr::BinaryOperatorClass:
194    return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
195  case Expr::CallExprClass:
196  case Expr::CXXMemberCallExprClass:
197  case Expr::CXXOperatorCallExprClass:
198    return EmitCallExprLValue(cast<CallExpr>(E));
199  case Expr::VAArgExprClass:
200    return EmitVAArgExprLValue(cast<VAArgExpr>(E));
201  case Expr::DeclRefExprClass:
202  case Expr::QualifiedDeclRefExprClass:
203    return EmitDeclRefLValue(cast<DeclRefExpr>(E));
204  case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
205  case Expr::PredefinedExprClass:
206    return EmitPredefinedLValue(cast<PredefinedExpr>(E));
207  case Expr::StringLiteralClass:
208    return EmitStringLiteralLValue(cast<StringLiteral>(E));
209  case Expr::ObjCEncodeExprClass:
210    return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
211
212  case Expr::BlockDeclRefExprClass:
213    return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
214
215  case Expr::CXXConditionDeclExprClass:
216    return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E));
217  case Expr::CXXTemporaryObjectExprClass:
218  case Expr::CXXConstructExprClass:
219    return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
220  case Expr::CXXBindTemporaryExprClass:
221    return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
222
223  case Expr::ObjCMessageExprClass:
224    return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
225  case Expr::ObjCIvarRefExprClass:
226    return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
227  case Expr::ObjCPropertyRefExprClass:
228    return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
229  case Expr::ObjCImplicitSetterGetterRefExprClass:
230    return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
231  case Expr::ObjCSuperExprClass:
232    return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E));
233
234  case Expr::StmtExprClass:
235    return EmitStmtExprLValue(cast<StmtExpr>(E));
236  case Expr::UnaryOperatorClass:
237    return EmitUnaryOpLValue(cast<UnaryOperator>(E));
238  case Expr::ArraySubscriptExprClass:
239    return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
240  case Expr::ExtVectorElementExprClass:
241    return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
242  case Expr::MemberExprClass:
243    return EmitMemberExpr(cast<MemberExpr>(E));
244  case Expr::CompoundLiteralExprClass:
245    return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
246  case Expr::ConditionalOperatorClass:
247    return EmitConditionalOperator(cast<ConditionalOperator>(E));
248  case Expr::ChooseExprClass:
249    return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
250  case Expr::ImplicitCastExprClass:
251  case Expr::CStyleCastExprClass:
252  case Expr::CXXFunctionalCastExprClass:
253  case Expr::CXXStaticCastExprClass:
254  case Expr::CXXDynamicCastExprClass:
255  case Expr::CXXReinterpretCastExprClass:
256  case Expr::CXXConstCastExprClass:
257    return EmitCastLValue(cast<CastExpr>(E));
258  }
259}
260
261llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
262                                               QualType Ty) {
263  llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp");
264
265  // Bool can have different representation in memory than in registers.
266  if (Ty->isBooleanType())
267    if (V->getType() != llvm::Type::getInt1Ty(VMContext))
268      V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool");
269
270  return V;
271}
272
273void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
274                                        bool Volatile, QualType Ty) {
275
276  if (Ty->isBooleanType()) {
277    // Bool can have different representation in memory than in registers.
278    const llvm::Type *SrcTy = Value->getType();
279    const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
280    if (DstPtr->getElementType() != SrcTy) {
281      const llvm::Type *MemTy =
282        llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
283      Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
284    }
285  }
286  Builder.CreateStore(Value, Addr, Volatile);
287}
288
289/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
290/// method emits the address of the lvalue, then loads the result as an rvalue,
291/// returning the rvalue.
292RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
293  if (LV.isObjCWeak()) {
294    // load of a __weak object.
295    llvm::Value *AddrWeakObj = LV.getAddress();
296    llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this,
297                                                                   AddrWeakObj);
298    return RValue::get(read_weak);
299  }
300
301  if (LV.isSimple()) {
302    llvm::Value *Ptr = LV.getAddress();
303    const llvm::Type *EltTy =
304      cast<llvm::PointerType>(Ptr->getType())->getElementType();
305
306    // Simple scalar l-value.
307    if (EltTy->isSingleValueType())
308      return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
309                                          ExprType));
310
311    assert(ExprType->isFunctionType() && "Unknown scalar value");
312    return RValue::get(Ptr);
313  }
314
315  if (LV.isVectorElt()) {
316    llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
317                                          LV.isVolatileQualified(), "tmp");
318    return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
319                                                    "vecext"));
320  }
321
322  // If this is a reference to a subset of the elements of a vector, either
323  // shuffle the input or extract/insert them as appropriate.
324  if (LV.isExtVectorElt())
325    return EmitLoadOfExtVectorElementLValue(LV, ExprType);
326
327  if (LV.isBitfield())
328    return EmitLoadOfBitfieldLValue(LV, ExprType);
329
330  if (LV.isPropertyRef())
331    return EmitLoadOfPropertyRefLValue(LV, ExprType);
332
333  assert(LV.isKVCRef() && "Unknown LValue type!");
334  return EmitLoadOfKVCRefLValue(LV, ExprType);
335}
336
337RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
338                                                 QualType ExprType) {
339  unsigned StartBit = LV.getBitfieldStartBit();
340  unsigned BitfieldSize = LV.getBitfieldSize();
341  llvm::Value *Ptr = LV.getBitfieldAddr();
342
343  const llvm::Type *EltTy =
344    cast<llvm::PointerType>(Ptr->getType())->getElementType();
345  unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
346
347  // In some cases the bitfield may straddle two memory locations.  Currently we
348  // load the entire bitfield, then do the magic to sign-extend it if
349  // necessary. This results in somewhat more code than necessary for the common
350  // case (one load), since two shifts accomplish both the masking and sign
351  // extension.
352  unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
353  llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
354
355  // Shift to proper location.
356  if (StartBit)
357    Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
358                             "bf.lo");
359
360  // Mask off unused bits.
361  llvm::Constant *LowMask = llvm::ConstantInt::get(VMContext,
362                                llvm::APInt::getLowBitsSet(EltTySize, LowBits));
363  Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
364
365  // Fetch the high bits if necessary.
366  if (LowBits < BitfieldSize) {
367    unsigned HighBits = BitfieldSize - LowBits;
368    llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
369                            llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
370    llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
371                                              LV.isVolatileQualified(),
372                                              "tmp");
373
374    // Mask off unused bits.
375    llvm::Constant *HighMask = llvm::ConstantInt::get(VMContext,
376                               llvm::APInt::getLowBitsSet(EltTySize, HighBits));
377    HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
378
379    // Shift to proper location and or in to bitfield value.
380    HighVal = Builder.CreateShl(HighVal,
381                                llvm::ConstantInt::get(EltTy, LowBits));
382    Val = Builder.CreateOr(Val, HighVal, "bf.val");
383  }
384
385  // Sign extend if necessary.
386  if (LV.isBitfieldSigned()) {
387    llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
388                                                    EltTySize - BitfieldSize);
389    Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
390                             ExtraBits, "bf.val.sext");
391  }
392
393  // The bitfield type and the normal type differ when the storage sizes differ
394  // (currently just _Bool).
395  Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
396
397  return RValue::get(Val);
398}
399
400RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
401                                                    QualType ExprType) {
402  return EmitObjCPropertyGet(LV.getPropertyRefExpr());
403}
404
405RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
406                                               QualType ExprType) {
407  return EmitObjCPropertyGet(LV.getKVCRefExpr());
408}
409
410// If this is a reference to a subset of the elements of a vector, create an
411// appropriate shufflevector.
412RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
413                                                         QualType ExprType) {
414  llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
415                                        LV.isVolatileQualified(), "tmp");
416
417  const llvm::Constant *Elts = LV.getExtVectorElts();
418
419  // If the result of the expression is a non-vector type, we must be extracting
420  // a single element.  Just codegen as an extractelement.
421  const VectorType *ExprVT = ExprType->getAsVectorType();
422  if (!ExprVT) {
423    unsigned InIdx = getAccessedFieldNo(0, Elts);
424    llvm::Value *Elt = llvm::ConstantInt::get(
425                                      llvm::Type::getInt32Ty(VMContext), InIdx);
426    return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
427  }
428
429  // Always use shuffle vector to try to retain the original program structure
430  unsigned NumResultElts = ExprVT->getNumElements();
431
432  llvm::SmallVector<llvm::Constant*, 4> Mask;
433  for (unsigned i = 0; i != NumResultElts; ++i) {
434    unsigned InIdx = getAccessedFieldNo(i, Elts);
435    Mask.push_back(llvm::ConstantInt::get(
436                                     llvm::Type::getInt32Ty(VMContext), InIdx));
437  }
438
439  llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
440  Vec = Builder.CreateShuffleVector(Vec,
441                                    llvm::UndefValue::get(Vec->getType()),
442                                    MaskV, "tmp");
443  return RValue::get(Vec);
444}
445
446
447
448/// EmitStoreThroughLValue - Store the specified rvalue into the specified
449/// lvalue, where both are guaranteed to the have the same type, and that type
450/// is 'Ty'.
451void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
452                                             QualType Ty) {
453  if (!Dst.isSimple()) {
454    if (Dst.isVectorElt()) {
455      // Read/modify/write the vector, inserting the new element.
456      llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
457                                            Dst.isVolatileQualified(), "tmp");
458      Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
459                                        Dst.getVectorIdx(), "vecins");
460      Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
461      return;
462    }
463
464    // If this is an update of extended vector elements, insert them as
465    // appropriate.
466    if (Dst.isExtVectorElt())
467      return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
468
469    if (Dst.isBitfield())
470      return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
471
472    if (Dst.isPropertyRef())
473      return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
474
475    if (Dst.isKVCRef())
476      return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
477
478    assert(0 && "Unknown LValue type");
479  }
480
481  if (Dst.isObjCWeak() && !Dst.isNonGC()) {
482    // load of a __weak object.
483    llvm::Value *LvalueDst = Dst.getAddress();
484    llvm::Value *src = Src.getScalarVal();
485     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
486    return;
487  }
488
489  if (Dst.isObjCStrong() && !Dst.isNonGC()) {
490    // load of a __strong object.
491    llvm::Value *LvalueDst = Dst.getAddress();
492    llvm::Value *src = Src.getScalarVal();
493#if 0
494    // FIXME: We cannot positively determine if we have an 'ivar' assignment,
495    // object assignment or an unknown assignment. For now, generate call to
496    // objc_assign_strongCast assignment which is a safe, but consevative
497    // assumption.
498    if (Dst.isObjCIvar())
499      CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst);
500    else
501      CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
502#endif
503    if (Dst.isGlobalObjCRef())
504      CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
505    else
506      CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
507    return;
508  }
509
510  assert(Src.isScalar() && "Can't emit an agg store with this method");
511  EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
512                    Dst.isVolatileQualified(), Ty);
513}
514
515void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
516                                                     QualType Ty,
517                                                     llvm::Value **Result) {
518  unsigned StartBit = Dst.getBitfieldStartBit();
519  unsigned BitfieldSize = Dst.getBitfieldSize();
520  llvm::Value *Ptr = Dst.getBitfieldAddr();
521
522  const llvm::Type *EltTy =
523    cast<llvm::PointerType>(Ptr->getType())->getElementType();
524  unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
525
526  // Get the new value, cast to the appropriate type and masked to exactly the
527  // size of the bit-field.
528  llvm::Value *SrcVal = Src.getScalarVal();
529  llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp");
530  llvm::Constant *Mask = llvm::ConstantInt::get(VMContext,
531                           llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
532  NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
533
534  // Return the new value of the bit-field, if requested.
535  if (Result) {
536    // Cast back to the proper type for result.
537    const llvm::Type *SrcTy = SrcVal->getType();
538    llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false,
539                                                  "bf.reload.val");
540
541    // Sign extend if necessary.
542    if (Dst.isBitfieldSigned()) {
543      unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy);
544      llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy,
545                                                      SrcTySize - BitfieldSize);
546      SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits),
547                                    ExtraBits, "bf.reload.sext");
548    }
549
550    *Result = SrcTrunc;
551  }
552
553  // In some cases the bitfield may straddle two memory locations.  Emit the low
554  // part first and check to see if the high needs to be done.
555  unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
556  llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
557                                           "bf.prev.low");
558
559  // Compute the mask for zero-ing the low part of this bitfield.
560  llvm::Constant *InvMask =
561    llvm::ConstantInt::get(VMContext,
562             ~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits));
563
564  // Compute the new low part as
565  //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
566  // with the shift of NewVal implicitly stripping the high bits.
567  llvm::Value *NewLowVal =
568    Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
569                      "bf.value.lo");
570  LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
571  LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
572
573  // Write back.
574  Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
575
576  // If the low part doesn't cover the bitfield emit a high part.
577  if (LowBits < BitfieldSize) {
578    unsigned HighBits = BitfieldSize - LowBits;
579    llvm::Value *HighPtr =  Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
580                            llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
581    llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
582                                              Dst.isVolatileQualified(),
583                                              "bf.prev.hi");
584
585    // Compute the mask for zero-ing the high part of this bitfield.
586    llvm::Constant *InvMask =
587      llvm::ConstantInt::get(VMContext, ~llvm::APInt::getLowBitsSet(EltTySize,
588                               HighBits));
589
590    // Compute the new high part as
591    //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
592    // where the high bits of NewVal have already been cleared and the
593    // shift stripping the low bits.
594    llvm::Value *NewHighVal =
595      Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
596                        "bf.value.high");
597    HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
598    HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
599
600    // Write back.
601    Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
602  }
603}
604
605void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
606                                                        LValue Dst,
607                                                        QualType Ty) {
608  EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
609}
610
611void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
612                                                   LValue Dst,
613                                                   QualType Ty) {
614  EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
615}
616
617void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
618                                                               LValue Dst,
619                                                               QualType Ty) {
620  // This access turns into a read/modify/write of the vector.  Load the input
621  // value now.
622  llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
623                                        Dst.isVolatileQualified(), "tmp");
624  const llvm::Constant *Elts = Dst.getExtVectorElts();
625
626  llvm::Value *SrcVal = Src.getScalarVal();
627
628  if (const VectorType *VTy = Ty->getAsVectorType()) {
629    unsigned NumSrcElts = VTy->getNumElements();
630    unsigned NumDstElts =
631       cast<llvm::VectorType>(Vec->getType())->getNumElements();
632    if (NumDstElts == NumSrcElts) {
633      // Use shuffle vector is the src and destination are the same number of
634      // elements and restore the vector mask since it is on the side it will be
635      // stored.
636      llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
637      for (unsigned i = 0; i != NumSrcElts; ++i) {
638        unsigned InIdx = getAccessedFieldNo(i, Elts);
639        Mask[InIdx] = llvm::ConstantInt::get(
640                                          llvm::Type::getInt32Ty(VMContext), i);
641      }
642
643      llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
644      Vec = Builder.CreateShuffleVector(SrcVal,
645                                        llvm::UndefValue::get(Vec->getType()),
646                                        MaskV, "tmp");
647    } else if (NumDstElts > NumSrcElts) {
648      // Extended the source vector to the same length and then shuffle it
649      // into the destination.
650      // FIXME: since we're shuffling with undef, can we just use the indices
651      //        into that?  This could be simpler.
652      llvm::SmallVector<llvm::Constant*, 4> ExtMask;
653      unsigned i;
654      for (i = 0; i != NumSrcElts; ++i)
655        ExtMask.push_back(llvm::ConstantInt::get(
656                                         llvm::Type::getInt32Ty(VMContext), i));
657      for (; i != NumDstElts; ++i)
658        ExtMask.push_back(llvm::UndefValue::get(
659                                            llvm::Type::getInt32Ty(VMContext)));
660      llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
661                                                        ExtMask.size());
662      llvm::Value *ExtSrcVal =
663        Builder.CreateShuffleVector(SrcVal,
664                                    llvm::UndefValue::get(SrcVal->getType()),
665                                    ExtMaskV, "tmp");
666      // build identity
667      llvm::SmallVector<llvm::Constant*, 4> Mask;
668      for (unsigned i = 0; i != NumDstElts; ++i) {
669        Mask.push_back(llvm::ConstantInt::get(
670                                        llvm::Type::getInt32Ty(VMContext), i));
671      }
672      // modify when what gets shuffled in
673      for (unsigned i = 0; i != NumSrcElts; ++i) {
674        unsigned Idx = getAccessedFieldNo(i, Elts);
675        Mask[Idx] = llvm::ConstantInt::get(
676                               llvm::Type::getInt32Ty(VMContext), i+NumDstElts);
677      }
678      llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
679      Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
680    } else {
681      // We should never shorten the vector
682      assert(0 && "unexpected shorten vector length");
683    }
684  } else {
685    // If the Src is a scalar (not a vector) it must be updating one element.
686    unsigned InIdx = getAccessedFieldNo(0, Elts);
687    llvm::Value *Elt = llvm::ConstantInt::get(
688                                      llvm::Type::getInt32Ty(VMContext), InIdx);
689    Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
690  }
691
692  Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
693}
694
695LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
696  const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
697
698  if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) ||
699        isa<ImplicitParamDecl>(VD))) {
700    LValue LV;
701    bool NonGCable = VD->hasLocalStorage() &&
702      !VD->hasAttr<BlocksAttr>();
703    if (VD->hasExternalStorage()) {
704      llvm::Value *V = CGM.GetAddrOfGlobalVar(VD);
705      if (VD->getType()->isReferenceType())
706        V = Builder.CreateLoad(V, "tmp");
707      LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
708                            getContext().getObjCGCAttrKind(E->getType()),
709                            E->getType().getAddressSpace());
710    } else {
711      llvm::Value *V = LocalDeclMap[VD];
712      assert(V && "DeclRefExpr not entered in LocalDeclMap?");
713      // local variables do not get their gc attribute set.
714      QualType::GCAttrTypes attr = QualType::GCNone;
715      // local static?
716      if (!NonGCable)
717        attr = getContext().getObjCGCAttrKind(E->getType());
718      if (VD->hasAttr<BlocksAttr>()) {
719        V = Builder.CreateStructGEP(V, 1, "forwarding");
720        V = Builder.CreateLoad(V, false);
721        V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
722                                    VD->getNameAsString());
723      }
724      if (VD->getType()->isReferenceType())
725        V = Builder.CreateLoad(V, "tmp");
726      LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr,
727                            E->getType().getAddressSpace());
728    }
729    LValue::SetObjCNonGC(LV, NonGCable);
730    return LV;
731  } else if (VD && VD->isFileVarDecl()) {
732    llvm::Value *V = CGM.GetAddrOfGlobalVar(VD);
733    if (VD->getType()->isReferenceType())
734      V = Builder.CreateLoad(V, "tmp");
735    LValue LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
736                                 getContext().getObjCGCAttrKind(E->getType()),
737                                 E->getType().getAddressSpace());
738    if (LV.isObjCStrong())
739      LV.SetGlobalObjCRef(LV, true);
740    return LV;
741  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
742    llvm::Value* V = CGM.GetAddrOfFunction(FD);
743    if (!FD->hasPrototype()) {
744      if (const FunctionProtoType *Proto =
745              FD->getType()->getAsFunctionProtoType()) {
746        // Ugly case: for a K&R-style definition, the type of the definition
747        // isn't the same as the type of a use.  Correct for this with a
748        // bitcast.
749        QualType NoProtoType =
750            getContext().getFunctionNoProtoType(Proto->getResultType());
751        NoProtoType = getContext().getPointerType(NoProtoType);
752        V = Builder.CreateBitCast(V, ConvertType(NoProtoType), "tmp");
753      }
754    }
755    return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
756                            getContext().getObjCGCAttrKind(E->getType()),
757                            E->getType().getAddressSpace());
758  } else if (const ImplicitParamDecl *IPD =
759      dyn_cast<ImplicitParamDecl>(E->getDecl())) {
760    llvm::Value *V = LocalDeclMap[IPD];
761    assert(V && "BlockVarDecl not entered in LocalDeclMap?");
762    return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
763                            getContext().getObjCGCAttrKind(E->getType()),
764                            E->getType().getAddressSpace());
765  }
766  assert(0 && "Unimp declref");
767  //an invalid LValue, but the assert will
768  //ensure that this point is never reached.
769  return LValue();
770}
771
772LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
773  return LValue::MakeAddr(GetAddrOfBlockDecl(E),
774                          E->getType().getCVRQualifiers(),
775                          getContext().getObjCGCAttrKind(E->getType()),
776                          E->getType().getAddressSpace());
777}
778
779LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
780  // __extension__ doesn't affect lvalue-ness.
781  if (E->getOpcode() == UnaryOperator::Extension)
782    return EmitLValue(E->getSubExpr());
783
784  QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
785  switch (E->getOpcode()) {
786  default: assert(0 && "Unknown unary operator lvalue!");
787  case UnaryOperator::Deref:
788    {
789      QualType T = E->getSubExpr()->getType()->getPointeeType();
790      assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
791
792      LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()),
793                                   T.getCVRQualifiers(),
794                                   getContext().getObjCGCAttrKind(T),
795                                   ExprTy.getAddressSpace());
796     // We should not generate __weak write barrier on indirect reference
797     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
798     // But, we continue to generate __strong write barrier on indirect write
799     // into a pointer to object.
800     if (getContext().getLangOptions().ObjC1 &&
801         getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
802         LV.isObjCWeak())
803       LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
804     return LV;
805    }
806  case UnaryOperator::Real:
807  case UnaryOperator::Imag:
808    LValue LV = EmitLValue(E->getSubExpr());
809    unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
810    return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
811                                                    Idx, "idx"),
812                            ExprTy.getCVRQualifiers(),
813                            QualType::GCNone,
814                            ExprTy.getAddressSpace());
815  }
816}
817
818LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
819  return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0);
820}
821
822LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
823  return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0);
824}
825
826
827LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
828  std::string GlobalVarName;
829
830  switch (Type) {
831  default:
832    assert(0 && "Invalid type");
833  case PredefinedExpr::Func:
834    GlobalVarName = "__func__.";
835    break;
836  case PredefinedExpr::Function:
837    GlobalVarName = "__FUNCTION__.";
838    break;
839  case PredefinedExpr::PrettyFunction:
840    GlobalVarName = "__PRETTY_FUNCTION__.";
841    break;
842  }
843
844  std::string FunctionName =
845    PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type,
846                                CurCodeDecl);
847
848  GlobalVarName += FunctionName;
849  llvm::Constant *C =
850    CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
851  return LValue::MakeAddr(C, 0);
852}
853
854LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
855  switch (E->getIdentType()) {
856  default:
857    return EmitUnsupportedLValue(E, "predefined expression");
858  case PredefinedExpr::Func:
859  case PredefinedExpr::Function:
860  case PredefinedExpr::PrettyFunction:
861    return EmitPredefinedFunctionName(E->getIdentType());
862  }
863}
864
865LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
866  // The index must always be an integer, which is not an aggregate.  Emit it.
867  llvm::Value *Idx = EmitScalarExpr(E->getIdx());
868  QualType IdxTy  = E->getIdx()->getType();
869  bool IdxSigned = IdxTy->isSignedIntegerType();
870
871  // If the base is a vector type, then we are forming a vector element lvalue
872  // with this subscript.
873  if (E->getBase()->getType()->isVectorType()) {
874    // Emit the vector as an lvalue to get its address.
875    LValue LHS = EmitLValue(E->getBase());
876    assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
877    Idx = Builder.CreateIntCast(Idx,
878                          llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx");
879    return LValue::MakeVectorElt(LHS.getAddress(), Idx,
880      E->getBase()->getType().getCVRQualifiers());
881  }
882
883  // The base must be a pointer, which is not an aggregate.  Emit it.
884  llvm::Value *Base = EmitScalarExpr(E->getBase());
885
886  // Extend or truncate the index type to 32 or 64-bits.
887  unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
888  if (IdxBitwidth != LLVMPointerWidth)
889    Idx = Builder.CreateIntCast(Idx,
890                            llvm::IntegerType::get(VMContext, LLVMPointerWidth),
891                                IdxSigned, "idxprom");
892
893  // We know that the pointer points to a type of the correct size, unless the
894  // size is a VLA or Objective-C interface.
895  llvm::Value *Address = 0;
896  if (const VariableArrayType *VAT =
897        getContext().getAsVariableArrayType(E->getType())) {
898    llvm::Value *VLASize = GetVLASize(VAT);
899
900    Idx = Builder.CreateMul(Idx, VLASize);
901
902    QualType BaseType = getContext().getBaseElementType(VAT);
903
904    uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8;
905    Idx = Builder.CreateUDiv(Idx,
906                             llvm::ConstantInt::get(Idx->getType(),
907                                                    BaseTypeSize));
908    Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
909  } else if (const ObjCInterfaceType *OIT =
910             dyn_cast<ObjCInterfaceType>(E->getType())) {
911    llvm::Value *InterfaceSize =
912      llvm::ConstantInt::get(Idx->getType(),
913                             getContext().getTypeSize(OIT) / 8);
914
915    Idx = Builder.CreateMul(Idx, InterfaceSize);
916
917    llvm::Type *i8PTy =
918            llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
919    Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
920                                Idx, "arrayidx");
921    Address = Builder.CreateBitCast(Address, Base->getType());
922  } else {
923    Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
924  }
925
926  QualType T = E->getBase()->getType()->getPointeeType();
927  assert(!T.isNull() &&
928         "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
929
930  LValue LV = LValue::MakeAddr(Address,
931                               T.getCVRQualifiers(),
932                               getContext().getObjCGCAttrKind(T),
933                               E->getBase()->getType().getAddressSpace());
934  if (getContext().getLangOptions().ObjC1 &&
935      getContext().getLangOptions().getGCMode() != LangOptions::NonGC)
936    LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
937  return LV;
938}
939
940static
941llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
942                                       llvm::SmallVector<unsigned, 4> &Elts) {
943  llvm::SmallVector<llvm::Constant *, 4> CElts;
944
945  for (unsigned i = 0, e = Elts.size(); i != e; ++i)
946    CElts.push_back(llvm::ConstantInt::get(
947                                   llvm::Type::getInt32Ty(VMContext), Elts[i]));
948
949  return llvm::ConstantVector::get(&CElts[0], CElts.size());
950}
951
952LValue CodeGenFunction::
953EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
954  // Emit the base vector as an l-value.
955  LValue Base;
956
957  // ExtVectorElementExpr's base can either be a vector or pointer to vector.
958  if (!E->isArrow()) {
959    assert(E->getBase()->getType()->isVectorType());
960    Base = EmitLValue(E->getBase());
961  } else {
962    const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
963    llvm::Value *Ptr = EmitScalarExpr(E->getBase());
964    Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers(),
965                            QualType::GCNone,
966                            PT->getPointeeType().getAddressSpace());
967  }
968
969  // Encode the element access list into a vector of unsigned indices.
970  llvm::SmallVector<unsigned, 4> Indices;
971  E->getEncodedElementAccess(Indices);
972
973  if (Base.isSimple()) {
974    llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
975    return LValue::MakeExtVectorElt(Base.getAddress(), CV,
976                                    Base.getQualifiers());
977  }
978  assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
979
980  llvm::Constant *BaseElts = Base.getExtVectorElts();
981  llvm::SmallVector<llvm::Constant *, 4> CElts;
982
983  for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
984    if (isa<llvm::ConstantAggregateZero>(BaseElts))
985      CElts.push_back(llvm::ConstantInt::get(
986                                         llvm::Type::getInt32Ty(VMContext), 0));
987    else
988      CElts.push_back(BaseElts->getOperand(Indices[i]));
989  }
990  llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
991  return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
992                                  Base.getQualifiers());
993}
994
995LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
996  bool isUnion = false;
997  bool isIvar = false;
998  bool isNonGC = false;
999  Expr *BaseExpr = E->getBase();
1000  llvm::Value *BaseValue = NULL;
1001  unsigned CVRQualifiers=0;
1002
1003  // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1004  if (E->isArrow()) {
1005    BaseValue = EmitScalarExpr(BaseExpr);
1006    const PointerType *PTy =
1007      BaseExpr->getType()->getAs<PointerType>();
1008    if (PTy->getPointeeType()->isUnionType())
1009      isUnion = true;
1010    CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
1011  } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1012             isa<ObjCImplicitSetterGetterRefExpr>(
1013               BaseExpr->IgnoreParens())) {
1014    RValue RV = EmitObjCPropertyGet(BaseExpr);
1015    BaseValue = RV.getAggregateAddr();
1016    if (BaseExpr->getType()->isUnionType())
1017      isUnion = true;
1018    CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
1019  } else {
1020    LValue BaseLV = EmitLValue(BaseExpr);
1021    if (BaseLV.isObjCIvar())
1022      isIvar = true;
1023    if (BaseLV.isNonGC())
1024      isNonGC = true;
1025    // FIXME: this isn't right for bitfields.
1026    BaseValue = BaseLV.getAddress();
1027    QualType BaseTy = BaseExpr->getType();
1028    if (BaseTy->isUnionType())
1029      isUnion = true;
1030    CVRQualifiers = BaseTy.getCVRQualifiers();
1031  }
1032
1033  FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl());
1034  // FIXME: Handle non-field member expressions
1035  assert(Field && "No code generation for non-field member references");
1036  LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion,
1037                                       CVRQualifiers);
1038  LValue::SetObjCIvar(MemExpLV, isIvar);
1039  LValue::SetObjCNonGC(MemExpLV, isNonGC);
1040  return MemExpLV;
1041}
1042
1043LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
1044                                              FieldDecl* Field,
1045                                              unsigned CVRQualifiers) {
1046  CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field);
1047
1048  // FIXME: CodeGenTypes should expose a method to get the appropriate type for
1049  // FieldTy (the appropriate type is ABI-dependent).
1050  const llvm::Type *FieldTy =
1051    CGM.getTypes().ConvertTypeForMem(Field->getType());
1052  const llvm::PointerType *BaseTy =
1053  cast<llvm::PointerType>(BaseValue->getType());
1054  unsigned AS = BaseTy->getAddressSpace();
1055  BaseValue = Builder.CreateBitCast(BaseValue,
1056                                    llvm::PointerType::get(FieldTy, AS),
1057                                    "tmp");
1058
1059  llvm::Value *Idx =
1060    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Info.FieldNo);
1061  llvm::Value *V = Builder.CreateGEP(BaseValue, Idx, "tmp");
1062
1063  return LValue::MakeBitfield(V, Info.Start, Info.Size,
1064                              Field->getType()->isSignedIntegerType(),
1065                            Field->getType().getCVRQualifiers()|CVRQualifiers);
1066}
1067
1068LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
1069                                           FieldDecl* Field,
1070                                           bool isUnion,
1071                                           unsigned CVRQualifiers) {
1072  if (Field->isBitField())
1073    return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1074
1075  unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1076  llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1077
1078  // Match union field type.
1079  if (isUnion) {
1080    const llvm::Type *FieldTy =
1081      CGM.getTypes().ConvertTypeForMem(Field->getType());
1082    const llvm::PointerType * BaseTy =
1083      cast<llvm::PointerType>(BaseValue->getType());
1084    unsigned AS = BaseTy->getAddressSpace();
1085    V = Builder.CreateBitCast(V,
1086                              llvm::PointerType::get(FieldTy, AS),
1087                              "tmp");
1088  }
1089  if (Field->getType()->isReferenceType())
1090    V = Builder.CreateLoad(V, "tmp");
1091
1092  QualType::GCAttrTypes attr = QualType::GCNone;
1093  if (CGM.getLangOptions().ObjC1 &&
1094      CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1095    QualType Ty = Field->getType();
1096    attr = Ty.getObjCGCAttr();
1097    if (attr != QualType::GCNone) {
1098      // __weak attribute on a field is ignored.
1099      if (attr == QualType::Weak)
1100        attr = QualType::GCNone;
1101    } else if (Ty->isObjCObjectPointerType())
1102      attr = QualType::Strong;
1103  }
1104  LValue LV =
1105    LValue::MakeAddr(V,
1106                     Field->getType().getCVRQualifiers()|CVRQualifiers,
1107                     attr,
1108                     Field->getType().getAddressSpace());
1109  return LV;
1110}
1111
1112LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){
1113  const llvm::Type *LTy = ConvertType(E->getType());
1114  llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
1115
1116  const Expr* InitExpr = E->getInitializer();
1117  LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers(),
1118                                   QualType::GCNone,
1119                                   E->getType().getAddressSpace());
1120
1121  if (E->getType()->isComplexType()) {
1122    EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
1123  } else if (hasAggregateLLVMType(E->getType())) {
1124    EmitAnyExpr(InitExpr, DeclPtr, false);
1125  } else {
1126    EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
1127  }
1128
1129  return Result;
1130}
1131
1132LValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator* E) {
1133  if (E->isLvalue(getContext()) == Expr::LV_Valid)
1134    return EmitUnsupportedLValue(E, "conditional operator");
1135
1136  // ?: here should be an aggregate.
1137  assert((hasAggregateLLVMType(E->getType()) &&
1138          !E->getType()->isAnyComplexType()) &&
1139         "Unexpected conditional operator!");
1140
1141  llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1142  EmitAggExpr(E, Temp, false);
1143
1144  return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1145                          getContext().getObjCGCAttrKind(E->getType()),
1146                          E->getType().getAddressSpace());
1147
1148}
1149
1150/// EmitCastLValue - Casts are never lvalues.  If a cast is needed by the code
1151/// generator in an lvalue context, then it must mean that we need the address
1152/// of an aggregate in order to access one of its fields.  This can happen for
1153/// all the reasons that casts are permitted with aggregate result, including
1154/// noop aggregate casts, and cast from scalar to union.
1155LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1156  switch (E->getCastKind()) {
1157  default:
1158    // If this is an lvalue cast, treat it as a no-op.
1159    // FIXME: We shouldn't need to check for this explicitly!
1160    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1161      if (ICE->isLvalueCast())
1162        return EmitLValue(E->getSubExpr());
1163
1164    assert(0 && "Unhandled cast!");
1165
1166  case CastExpr::CK_NoOp:
1167  case CastExpr::CK_ConstructorConversion:
1168  case CastExpr::CK_UserDefinedConversion:
1169    return EmitLValue(E->getSubExpr());
1170
1171  case CastExpr::CK_DerivedToBase: {
1172    const RecordType *DerivedClassTy =
1173      E->getSubExpr()->getType()->getAs<RecordType>();
1174    CXXRecordDecl *DerivedClassDecl =
1175      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1176
1177    const RecordType *BaseClassTy = E->getType()->getAs<RecordType>();
1178    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
1179
1180    LValue LV = EmitLValue(E->getSubExpr());
1181
1182    // Perform the derived-to-base conversion
1183    llvm::Value *Base =
1184      GetAddressCXXOfBaseClass(LV.getAddress(), DerivedClassDecl,
1185                               BaseClassDecl, /*NullCheckValue=*/false);
1186
1187    return LValue::MakeAddr(Base, E->getType().getCVRQualifiers(),
1188                            getContext().getObjCGCAttrKind(E->getType()),
1189                            E->getType().getAddressSpace());
1190  }
1191
1192  case CastExpr::CK_ToUnion: {
1193    llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1194    EmitAnyExpr(E->getSubExpr(), Temp, false);
1195
1196    return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1197                            getContext().getObjCGCAttrKind(E->getType()),
1198                            E->getType().getAddressSpace());
1199    }
1200  }
1201}
1202
1203//===--------------------------------------------------------------------===//
1204//                             Expression Emission
1205//===--------------------------------------------------------------------===//
1206
1207
1208RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
1209  // Builtins never have block type.
1210  if (E->getCallee()->getType()->isBlockPointerType())
1211    return EmitBlockCallExpr(E);
1212
1213  if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1214    return EmitCXXMemberCallExpr(CE);
1215
1216  const Decl *TargetDecl = 0;
1217  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1218    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1219      TargetDecl = DRE->getDecl();
1220      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1221        if (unsigned builtinID = FD->getBuiltinID())
1222          return EmitBuiltinExpr(FD, builtinID, E);
1223    }
1224  }
1225
1226  if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1227    if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1228      return EmitCXXOperatorMemberCallExpr(CE, MD);
1229
1230  if (isa<CXXPseudoDestructorExpr>(E->getCallee())) {
1231    // C++ [expr.pseudo]p1:
1232    //   The result shall only be used as the operand for the function call
1233    //   operator (), and the result of such a call has type void. The only
1234    //   effect is the evaluation of the postfix-expression before the dot or
1235    //   arrow.
1236    EmitScalarExpr(E->getCallee());
1237    return RValue::get(0);
1238  }
1239
1240  llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1241  return EmitCall(Callee, E->getCallee()->getType(),
1242                  E->arg_begin(), E->arg_end(), TargetDecl);
1243}
1244
1245LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1246  // Comma expressions just emit their LHS then their RHS as an l-value.
1247  if (E->getOpcode() == BinaryOperator::Comma) {
1248    EmitAnyExpr(E->getLHS());
1249    return EmitLValue(E->getRHS());
1250  }
1251
1252  // Can only get l-value for binary operator expressions which are a
1253  // simple assignment of aggregate type.
1254  if (E->getOpcode() != BinaryOperator::Assign)
1255    return EmitUnsupportedLValue(E, "binary l-value expression");
1256
1257  llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1258  EmitAggExpr(E, Temp, false);
1259  // FIXME: Are these qualifiers correct?
1260  return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1261                          getContext().getObjCGCAttrKind(E->getType()),
1262                          E->getType().getAddressSpace());
1263}
1264
1265LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1266  RValue RV = EmitCallExpr(E);
1267
1268  if (RV.isScalar()) {
1269    assert(E->getCallReturnType()->isReferenceType() &&
1270           "Can't have a scalar return unless the return type is a "
1271           "reference type!");
1272
1273    return LValue::MakeAddr(RV.getScalarVal(), E->getType().getCVRQualifiers(),
1274                            getContext().getObjCGCAttrKind(E->getType()),
1275                            E->getType().getAddressSpace());
1276  }
1277
1278  return LValue::MakeAddr(RV.getAggregateAddr(),
1279                          E->getType().getCVRQualifiers(),
1280                          getContext().getObjCGCAttrKind(E->getType()),
1281                          E->getType().getAddressSpace());
1282}
1283
1284LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
1285  // FIXME: This shouldn't require another copy.
1286  llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1287  EmitAggExpr(E, Temp, false);
1288  return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1289                          QualType::GCNone, E->getType().getAddressSpace());
1290}
1291
1292LValue
1293CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) {
1294  EmitLocalBlockVarDecl(*E->getVarDecl());
1295  return EmitDeclRefLValue(E);
1296}
1297
1298LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
1299  llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), "tmp");
1300  EmitCXXConstructExpr(Temp, E);
1301  return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1302                          QualType::GCNone, E->getType().getAddressSpace());
1303}
1304
1305LValue
1306CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
1307  LValue LV = EmitLValue(E->getSubExpr());
1308
1309  PushCXXTemporary(E->getTemporary(), LV.getAddress());
1310
1311  return LV;
1312}
1313
1314LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
1315  // Can only get l-value for message expression returning aggregate type
1316  RValue RV = EmitObjCMessageExpr(E);
1317  // FIXME: can this be volatile?
1318  return LValue::MakeAddr(RV.getAggregateAddr(),
1319                          E->getType().getCVRQualifiers(),
1320                          getContext().getObjCGCAttrKind(E->getType()),
1321                          E->getType().getAddressSpace());
1322}
1323
1324llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1325                                             const ObjCIvarDecl *Ivar) {
1326  return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
1327}
1328
1329LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
1330                                          llvm::Value *BaseValue,
1331                                          const ObjCIvarDecl *Ivar,
1332                                          unsigned CVRQualifiers) {
1333  return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
1334                                                   Ivar, CVRQualifiers);
1335}
1336
1337LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
1338  // FIXME: A lot of the code below could be shared with EmitMemberExpr.
1339  llvm::Value *BaseValue = 0;
1340  const Expr *BaseExpr = E->getBase();
1341  unsigned CVRQualifiers = 0;
1342  QualType ObjectTy;
1343  if (E->isArrow()) {
1344    BaseValue = EmitScalarExpr(BaseExpr);
1345    ObjectTy = BaseExpr->getType()->getPointeeType();
1346    CVRQualifiers = ObjectTy.getCVRQualifiers();
1347  } else {
1348    LValue BaseLV = EmitLValue(BaseExpr);
1349    // FIXME: this isn't right for bitfields.
1350    BaseValue = BaseLV.getAddress();
1351    ObjectTy = BaseExpr->getType();
1352    CVRQualifiers = ObjectTy.getCVRQualifiers();
1353  }
1354
1355  return EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), CVRQualifiers);
1356}
1357
1358LValue
1359CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1360  // This is a special l-value that just issues sends when we load or store
1361  // through it.
1362  return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
1363}
1364
1365LValue
1366CodeGenFunction::EmitObjCKVCRefLValue(
1367                                const ObjCImplicitSetterGetterRefExpr *E) {
1368  // This is a special l-value that just issues sends when we load or store
1369  // through it.
1370  return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
1371}
1372
1373LValue
1374CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) {
1375  return EmitUnsupportedLValue(E, "use of super");
1376}
1377
1378LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
1379
1380  // Can only get l-value for message expression returning aggregate type
1381  RValue RV = EmitAnyExprToTemp(E);
1382  // FIXME: can this be volatile?
1383  return LValue::MakeAddr(RV.getAggregateAddr(),
1384                          E->getType().getCVRQualifiers(),
1385                          getContext().getObjCGCAttrKind(E->getType()),
1386                          E->getType().getAddressSpace());
1387}
1388
1389
1390RValue CodeGenFunction::EmitCall(llvm::Value *Callee, QualType CalleeType,
1391                                 CallExpr::const_arg_iterator ArgBeg,
1392                                 CallExpr::const_arg_iterator ArgEnd,
1393                                 const Decl *TargetDecl) {
1394  // Get the actual function type. The callee type will always be a pointer to
1395  // function type or a block pointer type.
1396  assert(CalleeType->isFunctionPointerType() &&
1397         "Call must have function pointer type!");
1398
1399  QualType FnType = CalleeType->getAs<PointerType>()->getPointeeType();
1400  QualType ResultType = FnType->getAsFunctionType()->getResultType();
1401
1402  CallArgList Args;
1403  EmitCallArgs(Args, FnType->getAsFunctionProtoType(), ArgBeg, ArgEnd);
1404
1405  // FIXME: We should not need to do this, it should be part of the function
1406  // type.
1407  unsigned CallingConvention = 0;
1408  if (const llvm::Function *F =
1409      dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
1410    CallingConvention = F->getCallingConv();
1411  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1412                                                 CallingConvention),
1413                  Callee, Args, TargetDecl);
1414}
1415