]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/CodeGen/CGExpr.cpp
Vendor import of clang trunk r132879:
[FreeBSD/FreeBSD.git] / lib / CodeGen / CGExpr.cpp
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 "CGCXXABI.h"
18 #include "CGDebugInfo.h"
19 #include "CGRecordLayout.h"
20 #include "CGObjCRuntime.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "llvm/Intrinsics.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/Target/TargetData.h"
26 using namespace clang;
27 using namespace CodeGen;
28
29 //===--------------------------------------------------------------------===//
30 //                        Miscellaneous Helper Methods
31 //===--------------------------------------------------------------------===//
32
33 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
34   unsigned addressSpace =
35     cast<llvm::PointerType>(value->getType())->getAddressSpace();
36
37   const llvm::PointerType *destType = Int8PtrTy;
38   if (addressSpace)
39     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
40
41   if (value->getType() == destType) return value;
42   return Builder.CreateBitCast(value, destType);
43 }
44
45 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
46 /// block.
47 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
48                                                     const llvm::Twine &Name) {
49   if (!Builder.isNamePreserving())
50     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
51   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
52 }
53
54 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
55                                      llvm::Value *Init) {
56   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
57   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
58   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
59 }
60
61 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
62                                                 const llvm::Twine &Name) {
63   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
64   // FIXME: Should we prefer the preferred type alignment here?
65   CharUnits Align = getContext().getTypeAlignInChars(Ty);
66   Alloc->setAlignment(Align.getQuantity());
67   return Alloc;
68 }
69
70 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
71                                                  const llvm::Twine &Name) {
72   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
73   // FIXME: Should we prefer the preferred type alignment here?
74   CharUnits Align = getContext().getTypeAlignInChars(Ty);
75   Alloc->setAlignment(Align.getQuantity());
76   return Alloc;
77 }
78
79 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
80 /// expression and compare the result against zero, returning an Int1Ty value.
81 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
82   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
83     llvm::Value *MemPtr = EmitScalarExpr(E);
84     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
85   }
86
87   QualType BoolTy = getContext().BoolTy;
88   if (!E->getType()->isAnyComplexType())
89     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
90
91   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
92 }
93
94 /// EmitIgnoredExpr - Emit code to compute the specified expression,
95 /// ignoring the result.
96 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
97   if (E->isRValue())
98     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
99
100   // Just emit it as an l-value and drop the result.
101   EmitLValue(E);
102 }
103
104 /// EmitAnyExpr - Emit code to compute the specified expression which
105 /// can have any type.  The result is returned as an RValue struct.
106 /// If this is an aggregate expression, AggSlot indicates where the
107 /// result should be returned.
108 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
109                                     bool IgnoreResult) {
110   if (!hasAggregateLLVMType(E->getType()))
111     return RValue::get(EmitScalarExpr(E, IgnoreResult));
112   else if (E->getType()->isAnyComplexType())
113     return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
114
115   EmitAggExpr(E, AggSlot, IgnoreResult);
116   return AggSlot.asRValue();
117 }
118
119 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
120 /// always be accessible even if no aggregate location is provided.
121 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
122   AggValueSlot AggSlot = AggValueSlot::ignored();
123
124   if (hasAggregateLLVMType(E->getType()) &&
125       !E->getType()->isAnyComplexType())
126     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
127   return EmitAnyExpr(E, AggSlot);
128 }
129
130 /// EmitAnyExprToMem - Evaluate an expression into a given memory
131 /// location.
132 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
133                                        llvm::Value *Location,
134                                        bool IsLocationVolatile,
135                                        bool IsInit) {
136   if (E->getType()->isComplexType())
137     EmitComplexExprIntoAddr(E, Location, IsLocationVolatile);
138   else if (hasAggregateLLVMType(E->getType()))
139     EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit));
140   else {
141     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
142     LValue LV = MakeAddrLValue(Location, E->getType());
143     EmitStoreThroughLValue(RV, LV, E->getType());
144   }
145 }
146
147 namespace {
148 /// \brief An adjustment to be made to the temporary created when emitting a
149 /// reference binding, which accesses a particular subobject of that temporary.
150   struct SubobjectAdjustment {
151     enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
152
153     union {
154       struct {
155         const CastExpr *BasePath;
156         const CXXRecordDecl *DerivedClass;
157       } DerivedToBase;
158
159       FieldDecl *Field;
160     };
161
162     SubobjectAdjustment(const CastExpr *BasePath,
163                         const CXXRecordDecl *DerivedClass)
164       : Kind(DerivedToBaseAdjustment) {
165       DerivedToBase.BasePath = BasePath;
166       DerivedToBase.DerivedClass = DerivedClass;
167     }
168
169     SubobjectAdjustment(FieldDecl *Field)
170       : Kind(FieldAdjustment) {
171       this->Field = Field;
172     }
173   };
174 }
175
176 static llvm::Value *
177 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
178                          const NamedDecl *InitializedDecl) {
179   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
180     if (VD->hasGlobalStorage()) {
181       llvm::SmallString<256> Name;
182       llvm::raw_svector_ostream Out(Name);
183       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
184       Out.flush();
185
186       const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
187   
188       // Create the reference temporary.
189       llvm::GlobalValue *RefTemp =
190         new llvm::GlobalVariable(CGF.CGM.getModule(), 
191                                  RefTempTy, /*isConstant=*/false,
192                                  llvm::GlobalValue::InternalLinkage,
193                                  llvm::Constant::getNullValue(RefTempTy),
194                                  Name.str());
195       return RefTemp;
196     }
197   }
198
199   return CGF.CreateMemTemp(Type, "ref.tmp");
200 }
201
202 static llvm::Value *
203 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
204                             llvm::Value *&ReferenceTemporary,
205                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
206                             const NamedDecl *InitializedDecl) {
207   if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
208     E = DAE->getExpr();
209   
210   if (const ExprWithCleanups *TE = dyn_cast<ExprWithCleanups>(E)) {
211     CodeGenFunction::RunCleanupsScope Scope(CGF);
212
213     return EmitExprForReferenceBinding(CGF, TE->getSubExpr(), 
214                                        ReferenceTemporary, 
215                                        ReferenceTemporaryDtor,
216                                        InitializedDecl);
217   }
218
219   if (const ObjCPropertyRefExpr *PRE = 
220       dyn_cast<ObjCPropertyRefExpr>(E->IgnoreParenImpCasts()))
221     if (PRE->getGetterResultType()->isReferenceType())
222       E = PRE;
223     
224   RValue RV;
225   if (E->isGLValue()) {
226     // Emit the expression as an lvalue.
227     LValue LV = CGF.EmitLValue(E);
228     if (LV.isPropertyRef()) {
229       RV = CGF.EmitLoadOfPropertyRefLValue(LV);
230       return RV.getScalarVal();
231     }
232     if (LV.isSimple())
233       return LV.getAddress();
234     
235     // We have to load the lvalue.
236     RV = CGF.EmitLoadOfLValue(LV, E->getType());
237   } else {
238     llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
239     while (true) {
240       E = E->IgnoreParens();
241
242       if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
243         if ((CE->getCastKind() == CK_DerivedToBase ||
244              CE->getCastKind() == CK_UncheckedDerivedToBase) &&
245             E->getType()->isRecordType()) {
246           E = CE->getSubExpr();
247           CXXRecordDecl *Derived 
248             = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
249           Adjustments.push_back(SubobjectAdjustment(CE, Derived));
250           continue;
251         }
252
253         if (CE->getCastKind() == CK_NoOp) {
254           E = CE->getSubExpr();
255           continue;
256         }
257       } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
258         if (!ME->isArrow() && ME->getBase()->isRValue()) {
259           assert(ME->getBase()->getType()->isRecordType());
260           if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
261             E = ME->getBase();
262             Adjustments.push_back(SubobjectAdjustment(Field));
263             continue;
264           }
265         }
266       }
267
268       if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
269         if (opaque->getType()->isRecordType())
270           return CGF.EmitOpaqueValueLValue(opaque).getAddress();
271
272       // Nothing changed.
273       break;
274     }
275     
276     // Create a reference temporary if necessary.
277     AggValueSlot AggSlot = AggValueSlot::ignored();
278     if (CGF.hasAggregateLLVMType(E->getType()) &&
279         !E->getType()->isAnyComplexType()) {
280       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 
281                                                     InitializedDecl);
282       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false,
283                                       InitializedDecl != 0);
284     }
285       
286     RV = CGF.EmitAnyExpr(E, AggSlot);
287
288     if (InitializedDecl) {
289       // Get the destructor for the reference temporary.
290       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
291         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
292         if (!ClassDecl->hasTrivialDestructor())
293           ReferenceTemporaryDtor = ClassDecl->getDestructor();
294       }
295     }
296
297     // Check if need to perform derived-to-base casts and/or field accesses, to
298     // get from the temporary object we created (and, potentially, for which we
299     // extended the lifetime) to the subobject we're binding the reference to.
300     if (!Adjustments.empty()) {
301       llvm::Value *Object = RV.getAggregateAddr();
302       for (unsigned I = Adjustments.size(); I != 0; --I) {
303         SubobjectAdjustment &Adjustment = Adjustments[I-1];
304         switch (Adjustment.Kind) {
305         case SubobjectAdjustment::DerivedToBaseAdjustment:
306           Object = 
307               CGF.GetAddressOfBaseClass(Object, 
308                                         Adjustment.DerivedToBase.DerivedClass, 
309                               Adjustment.DerivedToBase.BasePath->path_begin(),
310                               Adjustment.DerivedToBase.BasePath->path_end(),
311                                         /*NullCheckValue=*/false);
312           break;
313             
314         case SubobjectAdjustment::FieldAdjustment: {
315           LValue LV = 
316             CGF.EmitLValueForField(Object, Adjustment.Field, 0);
317           if (LV.isSimple()) {
318             Object = LV.getAddress();
319             break;
320           }
321           
322           // For non-simple lvalues, we actually have to create a copy of
323           // the object we're binding to.
324           QualType T = Adjustment.Field->getType().getNonReferenceType()
325                                                   .getUnqualifiedType();
326           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
327           LValue TempLV = CGF.MakeAddrLValue(Object,
328                                              Adjustment.Field->getType());
329           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T);
330           break;
331         }
332
333         }
334       }
335
336       return Object;
337     }
338   }
339
340   if (RV.isAggregate())
341     return RV.getAggregateAddr();
342
343   // Create a temporary variable that we can bind the reference to.
344   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 
345                                                 InitializedDecl);
346
347
348   unsigned Alignment =
349     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
350   if (RV.isScalar())
351     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
352                           /*Volatile=*/false, Alignment, E->getType());
353   else
354     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
355                            /*Volatile=*/false);
356   return ReferenceTemporary;
357 }
358
359 RValue
360 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
361                                             const NamedDecl *InitializedDecl) {
362   llvm::Value *ReferenceTemporary = 0;
363   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
364   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
365                                                    ReferenceTemporaryDtor,
366                                                    InitializedDecl);
367   if (!ReferenceTemporaryDtor)
368     return RValue::get(Value);
369   
370   // Make sure to call the destructor for the reference temporary.
371   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
372     if (VD->hasGlobalStorage()) {
373       llvm::Constant *DtorFn = 
374         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
375       EmitCXXGlobalDtorRegistration(DtorFn, 
376                                     cast<llvm::Constant>(ReferenceTemporary));
377       
378       return RValue::get(Value);
379     }
380   }
381
382   PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
383
384   return RValue::get(Value);
385 }
386
387
388 /// getAccessedFieldNo - Given an encoded value and a result number, return the
389 /// input field number being accessed.
390 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
391                                              const llvm::Constant *Elts) {
392   if (isa<llvm::ConstantAggregateZero>(Elts))
393     return 0;
394
395   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
396 }
397
398 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
399   if (!CatchUndefined)
400     return;
401
402   // This needs to be to the standard address space.
403   Address = Builder.CreateBitCast(Address, Int8PtrTy);
404
405   const llvm::Type *IntPtrT = IntPtrTy;
406   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
407
408   // In time, people may want to control this and use a 1 here.
409   llvm::Value *Arg = Builder.getFalse();
410   llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
411   llvm::BasicBlock *Cont = createBasicBlock();
412   llvm::BasicBlock *Check = createBasicBlock();
413   llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
414   Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
415     
416   EmitBlock(Check);
417   Builder.CreateCondBr(Builder.CreateICmpUGE(C,
418                                         llvm::ConstantInt::get(IntPtrTy, Size)),
419                        Cont, getTrapBB());
420   EmitBlock(Cont);
421 }
422
423
424 CodeGenFunction::ComplexPairTy CodeGenFunction::
425 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
426                          bool isInc, bool isPre) {
427   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
428                                             LV.isVolatileQualified());
429   
430   llvm::Value *NextVal;
431   if (isa<llvm::IntegerType>(InVal.first->getType())) {
432     uint64_t AmountVal = isInc ? 1 : -1;
433     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
434     
435     // Add the inc/dec to the real part.
436     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
437   } else {
438     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
439     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
440     if (!isInc)
441       FVal.changeSign();
442     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
443     
444     // Add the inc/dec to the real part.
445     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
446   }
447   
448   ComplexPairTy IncVal(NextVal, InVal.second);
449   
450   // Store the updated result through the lvalue.
451   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
452   
453   // If this is a postinc, return the value read from memory, otherwise use the
454   // updated value.
455   return isPre ? IncVal : InVal;
456 }
457
458
459 //===----------------------------------------------------------------------===//
460 //                         LValue Expression Emission
461 //===----------------------------------------------------------------------===//
462
463 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
464   if (Ty->isVoidType())
465     return RValue::get(0);
466   
467   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
468     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
469     llvm::Value *U = llvm::UndefValue::get(EltTy);
470     return RValue::getComplex(std::make_pair(U, U));
471   }
472   
473   // If this is a use of an undefined aggregate type, the aggregate must have an
474   // identifiable address.  Just because the contents of the value are undefined
475   // doesn't mean that the address can't be taken and compared.
476   if (hasAggregateLLVMType(Ty)) {
477     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
478     return RValue::getAggregate(DestPtr);
479   }
480   
481   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
482 }
483
484 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
485                                               const char *Name) {
486   ErrorUnsupported(E, Name);
487   return GetUndefRValue(E->getType());
488 }
489
490 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
491                                               const char *Name) {
492   ErrorUnsupported(E, Name);
493   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
494   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
495 }
496
497 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
498   LValue LV = EmitLValue(E);
499   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
500     EmitCheck(LV.getAddress(), 
501               getContext().getTypeSizeInChars(E->getType()).getQuantity());
502   return LV;
503 }
504
505 /// EmitLValue - Emit code to compute a designator that specifies the location
506 /// of the expression.
507 ///
508 /// This can return one of two things: a simple address or a bitfield reference.
509 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
510 /// an LLVM pointer type.
511 ///
512 /// If this returns a bitfield reference, nothing about the pointee type of the
513 /// LLVM value is known: For example, it may not be a pointer to an integer.
514 ///
515 /// If this returns a normal address, and if the lvalue's C type is fixed size,
516 /// this method guarantees that the returned pointer type will point to an LLVM
517 /// type of the same size of the lvalue's type.  If the lvalue has a variable
518 /// length type, this is not possible.
519 ///
520 LValue CodeGenFunction::EmitLValue(const Expr *E) {
521   switch (E->getStmtClass()) {
522   default: return EmitUnsupportedLValue(E, "l-value expression");
523
524   case Expr::ObjCSelectorExprClass:
525   return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
526   case Expr::ObjCIsaExprClass:
527     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
528   case Expr::BinaryOperatorClass:
529     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
530   case Expr::CompoundAssignOperatorClass:
531     if (!E->getType()->isAnyComplexType())
532       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
533     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
534   case Expr::CallExprClass:
535   case Expr::CXXMemberCallExprClass:
536   case Expr::CXXOperatorCallExprClass:
537     return EmitCallExprLValue(cast<CallExpr>(E));
538   case Expr::VAArgExprClass:
539     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
540   case Expr::DeclRefExprClass:
541     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
542   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
543   case Expr::GenericSelectionExprClass:
544     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
545   case Expr::PredefinedExprClass:
546     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
547   case Expr::StringLiteralClass:
548     return EmitStringLiteralLValue(cast<StringLiteral>(E));
549   case Expr::ObjCEncodeExprClass:
550     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
551
552   case Expr::BlockDeclRefExprClass:
553     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
554
555   case Expr::CXXTemporaryObjectExprClass:
556   case Expr::CXXConstructExprClass:
557     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
558   case Expr::CXXBindTemporaryExprClass:
559     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
560   case Expr::ExprWithCleanupsClass:
561     return EmitExprWithCleanupsLValue(cast<ExprWithCleanups>(E));
562   case Expr::CXXScalarValueInitExprClass:
563     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
564   case Expr::CXXDefaultArgExprClass:
565     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
566   case Expr::CXXTypeidExprClass:
567     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
568
569   case Expr::ObjCMessageExprClass:
570     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
571   case Expr::ObjCIvarRefExprClass:
572     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
573   case Expr::ObjCPropertyRefExprClass:
574     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
575   case Expr::StmtExprClass:
576     return EmitStmtExprLValue(cast<StmtExpr>(E));
577   case Expr::UnaryOperatorClass:
578     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
579   case Expr::ArraySubscriptExprClass:
580     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
581   case Expr::ExtVectorElementExprClass:
582     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
583   case Expr::MemberExprClass:
584     return EmitMemberExpr(cast<MemberExpr>(E));
585   case Expr::CompoundLiteralExprClass:
586     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
587   case Expr::ConditionalOperatorClass:
588     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
589   case Expr::BinaryConditionalOperatorClass:
590     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
591   case Expr::ChooseExprClass:
592     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
593   case Expr::OpaqueValueExprClass:
594     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
595   case Expr::ImplicitCastExprClass:
596   case Expr::CStyleCastExprClass:
597   case Expr::CXXFunctionalCastExprClass:
598   case Expr::CXXStaticCastExprClass:
599   case Expr::CXXDynamicCastExprClass:
600   case Expr::CXXReinterpretCastExprClass:
601   case Expr::CXXConstCastExprClass:
602     return EmitCastLValue(cast<CastExpr>(E));
603   }
604 }
605
606 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
607                                               unsigned Alignment, QualType Ty,
608                                               llvm::MDNode *TBAAInfo) {
609   llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
610   if (Volatile)
611     Load->setVolatile(true);
612   if (Alignment)
613     Load->setAlignment(Alignment);
614   if (TBAAInfo)
615     CGM.DecorateInstruction(Load, TBAAInfo);
616
617   return EmitFromMemory(Load, Ty);
618 }
619
620 static bool isBooleanUnderlyingType(QualType Ty) {
621   if (const EnumType *ET = dyn_cast<EnumType>(Ty))
622     return ET->getDecl()->getIntegerType()->isBooleanType();
623   return false;
624 }
625
626 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
627   // Bool has a different representation in memory than in registers.
628   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
629     // This should really always be an i1, but sometimes it's already
630     // an i8, and it's awkward to track those cases down.
631     if (Value->getType()->isIntegerTy(1))
632       return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
633     assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
634   }
635
636   return Value;
637 }
638
639 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
640   // Bool has a different representation in memory than in registers.
641   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
642     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
643     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
644   }
645
646   return Value;
647 }
648
649 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
650                                         bool Volatile, unsigned Alignment,
651                                         QualType Ty,
652                                         llvm::MDNode *TBAAInfo) {
653   Value = EmitToMemory(Value, Ty);
654   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
655   if (Alignment)
656     Store->setAlignment(Alignment);
657   if (TBAAInfo)
658     CGM.DecorateInstruction(Store, TBAAInfo);
659 }
660
661 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
662 /// method emits the address of the lvalue, then loads the result as an rvalue,
663 /// returning the rvalue.
664 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
665   if (LV.isObjCWeak()) {
666     // load of a __weak object.
667     llvm::Value *AddrWeakObj = LV.getAddress();
668     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
669                                                              AddrWeakObj));
670   }
671
672   if (LV.isSimple()) {
673     llvm::Value *Ptr = LV.getAddress();
674
675     // Functions are l-values that don't require loading.
676     if (ExprType->isFunctionType())
677       return RValue::get(Ptr);
678
679     // Everything needs a load.
680     return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
681                                         LV.getAlignment(), ExprType,
682                                         LV.getTBAAInfo()));
683
684   }
685
686   if (LV.isVectorElt()) {
687     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
688                                           LV.isVolatileQualified(), "tmp");
689     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
690                                                     "vecext"));
691   }
692
693   // If this is a reference to a subset of the elements of a vector, either
694   // shuffle the input or extract/insert them as appropriate.
695   if (LV.isExtVectorElt())
696     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
697
698   if (LV.isBitField())
699     return EmitLoadOfBitfieldLValue(LV, ExprType);
700
701   assert(LV.isPropertyRef() && "Unknown LValue type!");
702   return EmitLoadOfPropertyRefLValue(LV);
703 }
704
705 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
706                                                  QualType ExprType) {
707   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
708
709   // Get the output type.
710   const llvm::Type *ResLTy = ConvertType(ExprType);
711   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
712
713   // Compute the result as an OR of all of the individual component accesses.
714   llvm::Value *Res = 0;
715   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
716     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
717
718     // Get the field pointer.
719     llvm::Value *Ptr = LV.getBitFieldBaseAddr();
720
721     // Only offset by the field index if used, so that incoming values are not
722     // required to be structures.
723     if (AI.FieldIndex)
724       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
725
726     // Offset by the byte offset, if used.
727     if (!AI.FieldByteOffset.isZero()) {
728       Ptr = EmitCastToVoidPtr(Ptr);
729       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
730                                        "bf.field.offs");
731     }
732
733     // Cast to the access type.
734     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(),
735                                                      AI.AccessWidth,
736                               CGM.getContext().getTargetAddressSpace(ExprType));
737     Ptr = Builder.CreateBitCast(Ptr, PTy);
738
739     // Perform the load.
740     llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
741     if (!AI.AccessAlignment.isZero())
742       Load->setAlignment(AI.AccessAlignment.getQuantity());
743
744     // Shift out unused low bits and mask out unused high bits.
745     llvm::Value *Val = Load;
746     if (AI.FieldBitStart)
747       Val = Builder.CreateLShr(Load, AI.FieldBitStart);
748     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
749                                                             AI.TargetBitWidth),
750                             "bf.clear");
751
752     // Extend or truncate to the target size.
753     if (AI.AccessWidth < ResSizeInBits)
754       Val = Builder.CreateZExt(Val, ResLTy);
755     else if (AI.AccessWidth > ResSizeInBits)
756       Val = Builder.CreateTrunc(Val, ResLTy);
757
758     // Shift into place, and OR into the result.
759     if (AI.TargetBitOffset)
760       Val = Builder.CreateShl(Val, AI.TargetBitOffset);
761     Res = Res ? Builder.CreateOr(Res, Val) : Val;
762   }
763
764   // If the bit-field is signed, perform the sign-extension.
765   //
766   // FIXME: This can easily be folded into the load of the high bits, which
767   // could also eliminate the mask of high bits in some situations.
768   if (Info.isSigned()) {
769     unsigned ExtraBits = ResSizeInBits - Info.getSize();
770     if (ExtraBits)
771       Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
772                                ExtraBits, "bf.val.sext");
773   }
774
775   return RValue::get(Res);
776 }
777
778 // If this is a reference to a subset of the elements of a vector, create an
779 // appropriate shufflevector.
780 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
781                                                          QualType ExprType) {
782   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
783                                         LV.isVolatileQualified(), "tmp");
784
785   const llvm::Constant *Elts = LV.getExtVectorElts();
786
787   // If the result of the expression is a non-vector type, we must be extracting
788   // a single element.  Just codegen as an extractelement.
789   const VectorType *ExprVT = ExprType->getAs<VectorType>();
790   if (!ExprVT) {
791     unsigned InIdx = getAccessedFieldNo(0, Elts);
792     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
793     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
794   }
795
796   // Always use shuffle vector to try to retain the original program structure
797   unsigned NumResultElts = ExprVT->getNumElements();
798
799   llvm::SmallVector<llvm::Constant*, 4> Mask;
800   for (unsigned i = 0; i != NumResultElts; ++i) {
801     unsigned InIdx = getAccessedFieldNo(i, Elts);
802     Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
803   }
804
805   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
806   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
807                                     MaskV, "tmp");
808   return RValue::get(Vec);
809 }
810
811
812
813 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
814 /// lvalue, where both are guaranteed to the have the same type, and that type
815 /// is 'Ty'.
816 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
817                                              QualType Ty) {
818   if (!Dst.isSimple()) {
819     if (Dst.isVectorElt()) {
820       // Read/modify/write the vector, inserting the new element.
821       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
822                                             Dst.isVolatileQualified(), "tmp");
823       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
824                                         Dst.getVectorIdx(), "vecins");
825       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
826       return;
827     }
828
829     // If this is an update of extended vector elements, insert them as
830     // appropriate.
831     if (Dst.isExtVectorElt())
832       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
833
834     if (Dst.isBitField())
835       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
836
837     assert(Dst.isPropertyRef() && "Unknown LValue type");
838     return EmitStoreThroughPropertyRefLValue(Src, Dst);
839   }
840
841   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
842     // load of a __weak object.
843     llvm::Value *LvalueDst = Dst.getAddress();
844     llvm::Value *src = Src.getScalarVal();
845      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
846     return;
847   }
848
849   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
850     // load of a __strong object.
851     llvm::Value *LvalueDst = Dst.getAddress();
852     llvm::Value *src = Src.getScalarVal();
853     if (Dst.isObjCIvar()) {
854       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
855       const llvm::Type *ResultType = ConvertType(getContext().LongTy);
856       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
857       llvm::Value *dst = RHS;
858       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
859       llvm::Value *LHS = 
860         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
861       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
862       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
863                                               BytesBetween);
864     } else if (Dst.isGlobalObjCRef()) {
865       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
866                                                 Dst.isThreadLocalRef());
867     }
868     else
869       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
870     return;
871   }
872
873   assert(Src.isScalar() && "Can't emit an agg store with this method");
874   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
875                     Dst.isVolatileQualified(), Dst.getAlignment(), Ty,
876                     Dst.getTBAAInfo());
877 }
878
879 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
880                                                      QualType Ty,
881                                                      llvm::Value **Result) {
882   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
883
884   // Get the output type.
885   const llvm::Type *ResLTy = ConvertTypeForMem(Ty);
886   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
887
888   // Get the source value, truncated to the width of the bit-field.
889   llvm::Value *SrcVal = Src.getScalarVal();
890
891   if (Ty->isBooleanType())
892     SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
893
894   SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
895                                                                 Info.getSize()),
896                              "bf.value");
897
898   // Return the new value of the bit-field, if requested.
899   if (Result) {
900     // Cast back to the proper type for result.
901     const llvm::Type *SrcTy = Src.getScalarVal()->getType();
902     llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
903                                                    "bf.reload.val");
904
905     // Sign extend if necessary.
906     if (Info.isSigned()) {
907       unsigned ExtraBits = ResSizeInBits - Info.getSize();
908       if (ExtraBits)
909         ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
910                                        ExtraBits, "bf.reload.sext");
911     }
912
913     *Result = ReloadVal;
914   }
915
916   // Iterate over the components, writing each piece to memory.
917   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
918     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
919
920     // Get the field pointer.
921     llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
922     unsigned addressSpace =
923       cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
924
925     // Only offset by the field index if used, so that incoming values are not
926     // required to be structures.
927     if (AI.FieldIndex)
928       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
929
930     // Offset by the byte offset, if used.
931     if (!AI.FieldByteOffset.isZero()) {
932       Ptr = EmitCastToVoidPtr(Ptr);
933       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
934                                        "bf.field.offs");
935     }
936
937     // Cast to the access type.
938     const llvm::Type *AccessLTy =
939       llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
940
941     const llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
942     Ptr = Builder.CreateBitCast(Ptr, PTy);
943
944     // Extract the piece of the bit-field value to write in this access, limited
945     // to the values that are part of this access.
946     llvm::Value *Val = SrcVal;
947     if (AI.TargetBitOffset)
948       Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
949     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
950                                                             AI.TargetBitWidth));
951
952     // Extend or truncate to the access size.
953     if (ResSizeInBits < AI.AccessWidth)
954       Val = Builder.CreateZExt(Val, AccessLTy);
955     else if (ResSizeInBits > AI.AccessWidth)
956       Val = Builder.CreateTrunc(Val, AccessLTy);
957
958     // Shift into the position in memory.
959     if (AI.FieldBitStart)
960       Val = Builder.CreateShl(Val, AI.FieldBitStart);
961
962     // If necessary, load and OR in bits that are outside of the bit-field.
963     if (AI.TargetBitWidth != AI.AccessWidth) {
964       llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
965       if (!AI.AccessAlignment.isZero())
966         Load->setAlignment(AI.AccessAlignment.getQuantity());
967
968       // Compute the mask for zeroing the bits that are part of the bit-field.
969       llvm::APInt InvMask =
970         ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
971                                  AI.FieldBitStart + AI.TargetBitWidth);
972
973       // Apply the mask and OR in to the value to write.
974       Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
975     }
976
977     // Write the value.
978     llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
979                                                  Dst.isVolatileQualified());
980     if (!AI.AccessAlignment.isZero())
981       Store->setAlignment(AI.AccessAlignment.getQuantity());
982   }
983 }
984
985 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
986                                                                LValue Dst,
987                                                                QualType Ty) {
988   // This access turns into a read/modify/write of the vector.  Load the input
989   // value now.
990   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
991                                         Dst.isVolatileQualified(), "tmp");
992   const llvm::Constant *Elts = Dst.getExtVectorElts();
993
994   llvm::Value *SrcVal = Src.getScalarVal();
995
996   if (const VectorType *VTy = Ty->getAs<VectorType>()) {
997     unsigned NumSrcElts = VTy->getNumElements();
998     unsigned NumDstElts =
999        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1000     if (NumDstElts == NumSrcElts) {
1001       // Use shuffle vector is the src and destination are the same number of
1002       // elements and restore the vector mask since it is on the side it will be
1003       // stored.
1004       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1005       for (unsigned i = 0; i != NumSrcElts; ++i) {
1006         unsigned InIdx = getAccessedFieldNo(i, Elts);
1007         Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
1008       }
1009
1010       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1011       Vec = Builder.CreateShuffleVector(SrcVal,
1012                                         llvm::UndefValue::get(Vec->getType()),
1013                                         MaskV, "tmp");
1014     } else if (NumDstElts > NumSrcElts) {
1015       // Extended the source vector to the same length and then shuffle it
1016       // into the destination.
1017       // FIXME: since we're shuffling with undef, can we just use the indices
1018       //        into that?  This could be simpler.
1019       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
1020       unsigned i;
1021       for (i = 0; i != NumSrcElts; ++i)
1022         ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1023       for (; i != NumDstElts; ++i)
1024         ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1025       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1026       llvm::Value *ExtSrcVal =
1027         Builder.CreateShuffleVector(SrcVal,
1028                                     llvm::UndefValue::get(SrcVal->getType()),
1029                                     ExtMaskV, "tmp");
1030       // build identity
1031       llvm::SmallVector<llvm::Constant*, 4> Mask;
1032       for (unsigned i = 0; i != NumDstElts; ++i)
1033         Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1034
1035       // modify when what gets shuffled in
1036       for (unsigned i = 0; i != NumSrcElts; ++i) {
1037         unsigned Idx = getAccessedFieldNo(i, Elts);
1038         Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1039       }
1040       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1041       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1042     } else {
1043       // We should never shorten the vector
1044       assert(0 && "unexpected shorten vector length");
1045     }
1046   } else {
1047     // If the Src is a scalar (not a vector) it must be updating one element.
1048     unsigned InIdx = getAccessedFieldNo(0, Elts);
1049     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1050     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1051   }
1052
1053   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1054 }
1055
1056 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1057 // generating write-barries API. It is currently a global, ivar,
1058 // or neither.
1059 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1060                                  LValue &LV) {
1061   if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1062     return;
1063   
1064   if (isa<ObjCIvarRefExpr>(E)) {
1065     LV.setObjCIvar(true);
1066     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1067     LV.setBaseIvarExp(Exp->getBase());
1068     LV.setObjCArray(E->getType()->isArrayType());
1069     return;
1070   }
1071   
1072   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1073     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1074       if (VD->hasGlobalStorage()) {
1075         LV.setGlobalObjCRef(true);
1076         LV.setThreadLocalRef(VD->isThreadSpecified());
1077       }
1078     }
1079     LV.setObjCArray(E->getType()->isArrayType());
1080     return;
1081   }
1082   
1083   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1084     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1085     return;
1086   }
1087   
1088   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1089     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1090     if (LV.isObjCIvar()) {
1091       // If cast is to a structure pointer, follow gcc's behavior and make it
1092       // a non-ivar write-barrier.
1093       QualType ExpTy = E->getType();
1094       if (ExpTy->isPointerType())
1095         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1096       if (ExpTy->isRecordType())
1097         LV.setObjCIvar(false); 
1098     }
1099     return;
1100   }
1101
1102   if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1103     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1104     return;
1105   }
1106
1107   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1108     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1109     return;
1110   }
1111   
1112   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1113     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1114     return;
1115   }
1116   
1117   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1118     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1119     if (LV.isObjCIvar() && !LV.isObjCArray()) 
1120       // Using array syntax to assigning to what an ivar points to is not 
1121       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1122       LV.setObjCIvar(false); 
1123     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1124       // Using array syntax to assigning to what global points to is not 
1125       // same as assigning to the global itself. {id *G;} G[i] = 0;
1126       LV.setGlobalObjCRef(false);
1127     return;
1128   }
1129   
1130   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1131     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1132     // We don't know if member is an 'ivar', but this flag is looked at
1133     // only in the context of LV.isObjCIvar().
1134     LV.setObjCArray(E->getType()->isArrayType());
1135     return;
1136   }
1137 }
1138
1139 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1140                                       const Expr *E, const VarDecl *VD) {
1141   assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1142          "Var decl must have external storage or be a file var decl!");
1143
1144   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1145   if (VD->getType()->isReferenceType())
1146     V = CGF.Builder.CreateLoad(V, "tmp");
1147   unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity();
1148   LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1149   setObjCGCLValueClass(CGF.getContext(), E, LV);
1150   return LV;
1151 }
1152
1153 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1154                                       const Expr *E, const FunctionDecl *FD) {
1155   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1156   if (!FD->hasPrototype()) {
1157     if (const FunctionProtoType *Proto =
1158             FD->getType()->getAs<FunctionProtoType>()) {
1159       // Ugly case: for a K&R-style definition, the type of the definition
1160       // isn't the same as the type of a use.  Correct for this with a
1161       // bitcast.
1162       QualType NoProtoType =
1163           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1164       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1165       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1166     }
1167   }
1168   unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity();
1169   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1170 }
1171
1172 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1173   const NamedDecl *ND = E->getDecl();
1174   unsigned Alignment = getContext().getDeclAlign(ND).getQuantity();
1175
1176   if (ND->hasAttr<WeakRefAttr>()) {
1177     const ValueDecl *VD = cast<ValueDecl>(ND);
1178     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1179     return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1180   }
1181
1182   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1183     
1184     // Check if this is a global variable.
1185     if (VD->hasExternalStorage() || VD->isFileVarDecl()) 
1186       return EmitGlobalVarDeclLValue(*this, E, VD);
1187
1188     bool NonGCable = VD->hasLocalStorage() &&
1189                      !VD->getType()->isReferenceType() &&
1190                      !VD->hasAttr<BlocksAttr>();
1191
1192     llvm::Value *V = LocalDeclMap[VD];
1193     if (!V && VD->isStaticLocal()) 
1194       V = CGM.getStaticLocalDeclAddress(VD);
1195     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1196
1197     if (VD->hasAttr<BlocksAttr>())
1198       V = BuildBlockByrefAddress(V, VD);
1199     
1200     if (VD->getType()->isReferenceType())
1201       V = Builder.CreateLoad(V, "tmp");
1202
1203     LValue LV = MakeAddrLValue(V, E->getType(), Alignment);
1204     if (NonGCable) {
1205       LV.getQuals().removeObjCGCAttr();
1206       LV.setNonGC(true);
1207     }
1208     setObjCGCLValueClass(getContext(), E, LV);
1209     return LV;
1210   }
1211
1212   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1213     return EmitFunctionDeclLValue(*this, E, fn);
1214
1215   assert(false && "Unhandled DeclRefExpr");
1216   
1217   // an invalid LValue, but the assert will
1218   // ensure that this point is never reached.
1219   return LValue();
1220 }
1221
1222 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1223   unsigned Alignment =
1224     getContext().getDeclAlign(E->getDecl()).getQuantity();
1225   return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
1226 }
1227
1228 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1229   // __extension__ doesn't affect lvalue-ness.
1230   if (E->getOpcode() == UO_Extension)
1231     return EmitLValue(E->getSubExpr());
1232
1233   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1234   switch (E->getOpcode()) {
1235   default: assert(0 && "Unknown unary operator lvalue!");
1236   case UO_Deref: {
1237     QualType T = E->getSubExpr()->getType()->getPointeeType();
1238     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1239
1240     LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1241     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1242
1243     // We should not generate __weak write barrier on indirect reference
1244     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1245     // But, we continue to generate __strong write barrier on indirect write
1246     // into a pointer to object.
1247     if (getContext().getLangOptions().ObjC1 &&
1248         getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1249         LV.isObjCWeak())
1250       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1251     return LV;
1252   }
1253   case UO_Real:
1254   case UO_Imag: {
1255     LValue LV = EmitLValue(E->getSubExpr());
1256     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1257     llvm::Value *Addr = LV.getAddress();
1258
1259     // real and imag are valid on scalars.  This is a faster way of
1260     // testing that.
1261     if (!cast<llvm::PointerType>(Addr->getType())
1262            ->getElementType()->isStructTy()) {
1263       assert(E->getSubExpr()->getType()->isArithmeticType());
1264       return LV;
1265     }
1266
1267     assert(E->getSubExpr()->getType()->isAnyComplexType());
1268
1269     unsigned Idx = E->getOpcode() == UO_Imag;
1270     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1271                                                   Idx, "idx"),
1272                           ExprTy);
1273   }
1274   case UO_PreInc:
1275   case UO_PreDec: {
1276     LValue LV = EmitLValue(E->getSubExpr());
1277     bool isInc = E->getOpcode() == UO_PreInc;
1278     
1279     if (E->getType()->isAnyComplexType())
1280       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1281     else
1282       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1283     return LV;
1284   }
1285   }
1286 }
1287
1288 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1289   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1290                         E->getType());
1291 }
1292
1293 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1294   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1295                         E->getType());
1296 }
1297
1298
1299 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1300   switch (E->getIdentType()) {
1301   default:
1302     return EmitUnsupportedLValue(E, "predefined expression");
1303
1304   case PredefinedExpr::Func:
1305   case PredefinedExpr::Function:
1306   case PredefinedExpr::PrettyFunction: {
1307     unsigned Type = E->getIdentType();
1308     std::string GlobalVarName;
1309
1310     switch (Type) {
1311     default: assert(0 && "Invalid type");
1312     case PredefinedExpr::Func:
1313       GlobalVarName = "__func__.";
1314       break;
1315     case PredefinedExpr::Function:
1316       GlobalVarName = "__FUNCTION__.";
1317       break;
1318     case PredefinedExpr::PrettyFunction:
1319       GlobalVarName = "__PRETTY_FUNCTION__.";
1320       break;
1321     }
1322
1323     llvm::StringRef FnName = CurFn->getName();
1324     if (FnName.startswith("\01"))
1325       FnName = FnName.substr(1);
1326     GlobalVarName += FnName;
1327
1328     const Decl *CurDecl = CurCodeDecl;
1329     if (CurDecl == 0)
1330       CurDecl = getContext().getTranslationUnitDecl();
1331
1332     std::string FunctionName =
1333         (isa<BlockDecl>(CurDecl)
1334          ? FnName.str()
1335          : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl));
1336
1337     llvm::Constant *C =
1338       CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1339     return MakeAddrLValue(C, E->getType());
1340   }
1341   }
1342 }
1343
1344 llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1345   const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1346
1347   // If we are not optimzing, don't collapse all calls to trap in the function
1348   // to the same call, that way, in the debugger they can see which operation
1349   // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1350   // to just one per function to save on codesize.
1351   if (GCO.OptimizationLevel && TrapBB)
1352     return TrapBB;
1353
1354   llvm::BasicBlock *Cont = 0;
1355   if (HaveInsertPoint()) {
1356     Cont = createBasicBlock("cont");
1357     EmitBranch(Cont);
1358   }
1359   TrapBB = createBasicBlock("trap");
1360   EmitBlock(TrapBB);
1361
1362   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1363   llvm::CallInst *TrapCall = Builder.CreateCall(F);
1364   TrapCall->setDoesNotReturn();
1365   TrapCall->setDoesNotThrow();
1366   Builder.CreateUnreachable();
1367
1368   if (Cont)
1369     EmitBlock(Cont);
1370   return TrapBB;
1371 }
1372
1373 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1374 /// array to pointer, return the array subexpression.
1375 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1376   // If this isn't just an array->pointer decay, bail out.
1377   const CastExpr *CE = dyn_cast<CastExpr>(E);
1378   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1379     return 0;
1380   
1381   // If this is a decay from variable width array, bail out.
1382   const Expr *SubExpr = CE->getSubExpr();
1383   if (SubExpr->getType()->isVariableArrayType())
1384     return 0;
1385   
1386   return SubExpr;
1387 }
1388
1389 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1390   // The index must always be an integer, which is not an aggregate.  Emit it.
1391   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1392   QualType IdxTy  = E->getIdx()->getType();
1393   bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
1394
1395   // If the base is a vector type, then we are forming a vector element lvalue
1396   // with this subscript.
1397   if (E->getBase()->getType()->isVectorType()) {
1398     // Emit the vector as an lvalue to get its address.
1399     LValue LHS = EmitLValue(E->getBase());
1400     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1401     Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
1402     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1403                                  E->getBase()->getType().getCVRQualifiers());
1404   }
1405
1406   // Extend or truncate the index type to 32 or 64-bits.
1407   if (Idx->getType() != IntPtrTy)
1408     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
1409   
1410   // FIXME: As llvm implements the object size checking, this can come out.
1411   if (CatchUndefined) {
1412     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1413       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1414         if (ICE->getCastKind() == CK_ArrayToPointerDecay) {
1415           if (const ConstantArrayType *CAT
1416               = getContext().getAsConstantArrayType(DRE->getType())) {
1417             llvm::APInt Size = CAT->getSize();
1418             llvm::BasicBlock *Cont = createBasicBlock("cont");
1419             Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1420                                   llvm::ConstantInt::get(Idx->getType(), Size)),
1421                                  Cont, getTrapBB());
1422             EmitBlock(Cont);
1423           }
1424         }
1425       }
1426     }
1427   }
1428
1429   // We know that the pointer points to a type of the correct size, unless the
1430   // size is a VLA or Objective-C interface.
1431   llvm::Value *Address = 0;
1432   unsigned ArrayAlignment = 0;
1433   if (const VariableArrayType *VAT =
1434         getContext().getAsVariableArrayType(E->getType())) {
1435     llvm::Value *VLASize = GetVLASize(VAT);
1436
1437     Idx = Builder.CreateMul(Idx, VLASize);
1438
1439     // The base must be a pointer, which is not an aggregate.  Emit it.
1440     llvm::Value *Base = EmitScalarExpr(E->getBase());
1441
1442     Address = EmitCastToVoidPtr(Base);
1443     if (getContext().getLangOptions().isSignedOverflowDefined())
1444       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1445     else
1446       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
1447     Address = Builder.CreateBitCast(Address, Base->getType());
1448   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1449     // Indexing over an interface, as in "NSString *P; P[4];"
1450     llvm::Value *InterfaceSize =
1451       llvm::ConstantInt::get(Idx->getType(),
1452           getContext().getTypeSizeInChars(OIT).getQuantity());
1453
1454     Idx = Builder.CreateMul(Idx, InterfaceSize);
1455
1456     // The base must be a pointer, which is not an aggregate.  Emit it.
1457     llvm::Value *Base = EmitScalarExpr(E->getBase());
1458     Address = EmitCastToVoidPtr(Base);
1459     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1460     Address = Builder.CreateBitCast(Address, Base->getType());
1461   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1462     // If this is A[i] where A is an array, the frontend will have decayed the
1463     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1464     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1465     // "gep x, i" here.  Emit one "gep A, 0, i".
1466     assert(Array->getType()->isArrayType() &&
1467            "Array to pointer decay must have array source type!");
1468     LValue ArrayLV = EmitLValue(Array);
1469     llvm::Value *ArrayPtr = ArrayLV.getAddress();
1470     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1471     llvm::Value *Args[] = { Zero, Idx };
1472     
1473     // Propagate the alignment from the array itself to the result.
1474     ArrayAlignment = ArrayLV.getAlignment();
1475
1476     if (getContext().getLangOptions().isSignedOverflowDefined())
1477       Address = Builder.CreateGEP(ArrayPtr, Args, Args+2, "arrayidx");
1478     else
1479       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1480   } else {
1481     // The base must be a pointer, which is not an aggregate.  Emit it.
1482     llvm::Value *Base = EmitScalarExpr(E->getBase());
1483     if (getContext().getLangOptions().isSignedOverflowDefined())
1484       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1485     else
1486       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1487   }
1488
1489   QualType T = E->getBase()->getType()->getPointeeType();
1490   assert(!T.isNull() &&
1491          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1492
1493   // Limit the alignment to that of the result type.
1494   if (ArrayAlignment) {
1495     unsigned Align = getContext().getTypeAlignInChars(T).getQuantity();
1496     ArrayAlignment = std::min(Align, ArrayAlignment);
1497   }
1498
1499   LValue LV = MakeAddrLValue(Address, T, ArrayAlignment);
1500   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1501
1502   if (getContext().getLangOptions().ObjC1 &&
1503       getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1504     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1505     setObjCGCLValueClass(getContext(), E, LV);
1506   }
1507   return LV;
1508 }
1509
1510 static
1511 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1512                                        llvm::SmallVector<unsigned, 4> &Elts) {
1513   llvm::SmallVector<llvm::Constant*, 4> CElts;
1514
1515   const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1516   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1517     CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1518
1519   return llvm::ConstantVector::get(CElts);
1520 }
1521
1522 LValue CodeGenFunction::
1523 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1524   // Emit the base vector as an l-value.
1525   LValue Base;
1526
1527   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1528   if (E->isArrow()) {
1529     // If it is a pointer to a vector, emit the address and form an lvalue with
1530     // it.
1531     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1532     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1533     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1534     Base.getQuals().removeObjCGCAttr();
1535   } else if (E->getBase()->isGLValue()) {
1536     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1537     // emit the base as an lvalue.
1538     assert(E->getBase()->getType()->isVectorType());
1539     Base = EmitLValue(E->getBase());
1540   } else {
1541     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1542     assert(E->getBase()->getType()->getAs<VectorType>() &&
1543            "Result must be a vector");
1544     llvm::Value *Vec = EmitScalarExpr(E->getBase());
1545     
1546     // Store the vector to memory (because LValue wants an address).
1547     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1548     Builder.CreateStore(Vec, VecMem);
1549     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1550   }
1551   
1552   // Encode the element access list into a vector of unsigned indices.
1553   llvm::SmallVector<unsigned, 4> Indices;
1554   E->getEncodedElementAccess(Indices);
1555
1556   if (Base.isSimple()) {
1557     llvm::Constant *CV = GenerateConstantVector(getLLVMContext(), Indices);
1558     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1559                                     Base.getVRQualifiers());
1560   }
1561   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1562
1563   llvm::Constant *BaseElts = Base.getExtVectorElts();
1564   llvm::SmallVector<llvm::Constant *, 4> CElts;
1565
1566   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1567     if (isa<llvm::ConstantAggregateZero>(BaseElts))
1568       CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1569     else
1570       CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1571   }
1572   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
1573   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1574                                   Base.getVRQualifiers());
1575 }
1576
1577 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1578   bool isNonGC = false;
1579   Expr *BaseExpr = E->getBase();
1580   llvm::Value *BaseValue = NULL;
1581   Qualifiers BaseQuals;
1582
1583   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1584   if (E->isArrow()) {
1585     BaseValue = EmitScalarExpr(BaseExpr);
1586     const PointerType *PTy =
1587       BaseExpr->getType()->getAs<PointerType>();
1588     BaseQuals = PTy->getPointeeType().getQualifiers();
1589   } else {
1590     LValue BaseLV = EmitLValue(BaseExpr);
1591     if (BaseLV.isNonGC())
1592       isNonGC = true;
1593     // FIXME: this isn't right for bitfields.
1594     BaseValue = BaseLV.getAddress();
1595     QualType BaseTy = BaseExpr->getType();
1596     BaseQuals = BaseTy.getQualifiers();
1597   }
1598
1599   NamedDecl *ND = E->getMemberDecl();
1600   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1601     LValue LV = EmitLValueForField(BaseValue, Field, 
1602                                    BaseQuals.getCVRQualifiers());
1603     LV.setNonGC(isNonGC);
1604     setObjCGCLValueClass(getContext(), E, LV);
1605     return LV;
1606   }
1607   
1608   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1609     return EmitGlobalVarDeclLValue(*this, E, VD);
1610
1611   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1612     return EmitFunctionDeclLValue(*this, E, FD);
1613
1614   assert(false && "Unhandled member declaration!");
1615   return LValue();
1616 }
1617
1618 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1619                                               const FieldDecl *Field,
1620                                               unsigned CVRQualifiers) {
1621   const CGRecordLayout &RL =
1622     CGM.getTypes().getCGRecordLayout(Field->getParent());
1623   const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1624   return LValue::MakeBitfield(BaseValue, Info,
1625                              Field->getType().getCVRQualifiers()|CVRQualifiers);
1626 }
1627
1628 /// EmitLValueForAnonRecordField - Given that the field is a member of
1629 /// an anonymous struct or union buried inside a record, and given
1630 /// that the base value is a pointer to the enclosing record, derive
1631 /// an lvalue for the ultimate field.
1632 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1633                                              const IndirectFieldDecl *Field,
1634                                                      unsigned CVRQualifiers) {
1635   IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
1636     IEnd = Field->chain_end();
1637   while (true) {
1638     LValue LV = EmitLValueForField(BaseValue, cast<FieldDecl>(*I),
1639                                    CVRQualifiers);
1640     if (++I == IEnd) return LV;
1641
1642     assert(LV.isSimple());
1643     BaseValue = LV.getAddress();
1644     CVRQualifiers |= LV.getVRQualifiers();
1645   }
1646 }
1647
1648 LValue CodeGenFunction::EmitLValueForField(llvm::Value *baseAddr,
1649                                            const FieldDecl *field,
1650                                            unsigned cvr) {
1651   if (field->isBitField())
1652     return EmitLValueForBitfield(baseAddr, field, cvr);
1653
1654   const RecordDecl *rec = field->getParent();
1655   QualType type = field->getType();
1656
1657   bool mayAlias = rec->hasAttr<MayAliasAttr>();
1658
1659   llvm::Value *addr;
1660   if (rec->isUnion()) {
1661     // For unions, we just cast to the appropriate type.
1662     assert(!type->isReferenceType() && "union has reference member");
1663
1664     const llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(type);
1665     unsigned AS =
1666       cast<llvm::PointerType>(baseAddr->getType())->getAddressSpace();
1667     addr = Builder.CreateBitCast(baseAddr, llvmType->getPointerTo(AS),
1668                                  field->getName());
1669   } else {
1670     // For structs, we GEP to the field that the record layout suggests.
1671     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
1672     addr = Builder.CreateStructGEP(baseAddr, idx, field->getName());
1673
1674     // If this is a reference field, load the reference right now.
1675     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
1676       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
1677       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
1678
1679       if (CGM.shouldUseTBAA()) {
1680         llvm::MDNode *tbaa;
1681         if (mayAlias)
1682           tbaa = CGM.getTBAAInfo(getContext().CharTy);
1683         else
1684           tbaa = CGM.getTBAAInfo(type);
1685         CGM.DecorateInstruction(load, tbaa);
1686       }
1687
1688       addr = load;
1689       mayAlias = false;
1690       type = refType->getPointeeType();
1691       cvr = 0; // qualifiers don't recursively apply to referencee
1692     }
1693   }
1694
1695   unsigned alignment = getContext().getDeclAlign(field).getQuantity();
1696   LValue LV = MakeAddrLValue(addr, type, alignment);
1697   LV.getQuals().addCVRQualifiers(cvr);
1698
1699   // __weak attribute on a field is ignored.
1700   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
1701     LV.getQuals().removeObjCGCAttr();
1702
1703   // Fields of may_alias structs act like 'char' for TBAA purposes.
1704   // FIXME: this should get propagated down through anonymous structs
1705   // and unions.
1706   if (mayAlias && LV.getTBAAInfo())
1707     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
1708
1709   return LV;
1710 }
1711
1712 LValue 
1713 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue, 
1714                                                   const FieldDecl *Field,
1715                                                   unsigned CVRQualifiers) {
1716   QualType FieldType = Field->getType();
1717   
1718   if (!FieldType->isReferenceType())
1719     return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1720
1721   const CGRecordLayout &RL =
1722     CGM.getTypes().getCGRecordLayout(Field->getParent());
1723   unsigned idx = RL.getLLVMFieldNo(Field);
1724   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1725
1726   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1727
1728   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1729   return MakeAddrLValue(V, FieldType, Alignment);
1730 }
1731
1732 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
1733   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1734   const Expr *InitExpr = E->getInitializer();
1735   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
1736
1737   EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true);
1738
1739   return Result;
1740 }
1741
1742 LValue CodeGenFunction::
1743 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
1744   if (!expr->isGLValue()) {
1745     // ?: here should be an aggregate.
1746     assert((hasAggregateLLVMType(expr->getType()) &&
1747             !expr->getType()->isAnyComplexType()) &&
1748            "Unexpected conditional operator!");
1749     return EmitAggExprToLValue(expr);
1750   }
1751
1752   const Expr *condExpr = expr->getCond();
1753   bool CondExprBool;
1754   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
1755     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
1756     if (!CondExprBool) std::swap(live, dead);
1757
1758     if (!ContainsLabel(dead))
1759       return EmitLValue(live);
1760   }
1761
1762   OpaqueValueMapping binding(*this, expr);
1763
1764   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
1765   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
1766   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
1767
1768   ConditionalEvaluation eval(*this);
1769   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
1770     
1771   // Any temporaries created here are conditional.
1772   EmitBlock(lhsBlock);
1773   eval.begin(*this);
1774   LValue lhs = EmitLValue(expr->getTrueExpr());
1775   eval.end(*this);
1776     
1777   if (!lhs.isSimple())
1778     return EmitUnsupportedLValue(expr, "conditional operator");
1779
1780   lhsBlock = Builder.GetInsertBlock();
1781   Builder.CreateBr(contBlock);
1782     
1783   // Any temporaries created here are conditional.
1784   EmitBlock(rhsBlock);
1785   eval.begin(*this);
1786   LValue rhs = EmitLValue(expr->getFalseExpr());
1787   eval.end(*this);
1788   if (!rhs.isSimple())
1789     return EmitUnsupportedLValue(expr, "conditional operator");
1790   rhsBlock = Builder.GetInsertBlock();
1791
1792   EmitBlock(contBlock);
1793
1794   llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
1795                                          "cond-lvalue");
1796   phi->addIncoming(lhs.getAddress(), lhsBlock);
1797   phi->addIncoming(rhs.getAddress(), rhsBlock);
1798   return MakeAddrLValue(phi, expr->getType());
1799 }
1800
1801 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1802 /// If the cast is a dynamic_cast, we can have the usual lvalue result,
1803 /// otherwise if a cast is needed by the code generator in an lvalue context,
1804 /// then it must mean that we need the address of an aggregate in order to
1805 /// access one of its fields.  This can happen for all the reasons that casts
1806 /// are permitted with aggregate result, including noop aggregate casts, and
1807 /// cast from scalar to union.
1808 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1809   switch (E->getCastKind()) {
1810   case CK_ToVoid:
1811     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1812
1813   case CK_Dependent:
1814     llvm_unreachable("dependent cast kind in IR gen!");
1815
1816   case CK_GetObjCProperty: {
1817     LValue LV = EmitLValue(E->getSubExpr());
1818     assert(LV.isPropertyRef());
1819     RValue RV = EmitLoadOfPropertyRefLValue(LV);
1820
1821     // Property is an aggregate r-value.
1822     if (RV.isAggregate()) {
1823       return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
1824     }
1825
1826     // Implicit property returns an l-value.
1827     assert(RV.isScalar());
1828     return MakeAddrLValue(RV.getScalarVal(), E->getSubExpr()->getType());
1829   }
1830
1831   case CK_NoOp:
1832   case CK_LValueToRValue:
1833     if (!E->getSubExpr()->Classify(getContext()).isPRValue() 
1834         || E->getType()->isRecordType())
1835       return EmitLValue(E->getSubExpr());
1836     // Fall through to synthesize a temporary.
1837
1838   case CK_BitCast:
1839   case CK_ArrayToPointerDecay:
1840   case CK_FunctionToPointerDecay:
1841   case CK_NullToMemberPointer:
1842   case CK_NullToPointer:
1843   case CK_IntegralToPointer:
1844   case CK_PointerToIntegral:
1845   case CK_PointerToBoolean:
1846   case CK_VectorSplat:
1847   case CK_IntegralCast:
1848   case CK_IntegralToBoolean:
1849   case CK_IntegralToFloating:
1850   case CK_FloatingToIntegral:
1851   case CK_FloatingToBoolean:
1852   case CK_FloatingCast:
1853   case CK_FloatingRealToComplex:
1854   case CK_FloatingComplexToReal:
1855   case CK_FloatingComplexToBoolean:
1856   case CK_FloatingComplexCast:
1857   case CK_FloatingComplexToIntegralComplex:
1858   case CK_IntegralRealToComplex:
1859   case CK_IntegralComplexToReal:
1860   case CK_IntegralComplexToBoolean:
1861   case CK_IntegralComplexCast:
1862   case CK_IntegralComplexToFloatingComplex:
1863   case CK_DerivedToBaseMemberPointer:
1864   case CK_BaseToDerivedMemberPointer:
1865   case CK_MemberPointerToBoolean:
1866   case CK_AnyPointerToBlockPointerCast: {
1867     // These casts only produce lvalues when we're binding a reference to a 
1868     // temporary realized from a (converted) pure rvalue. Emit the expression
1869     // as a value, copy it into a temporary, and return an lvalue referring to
1870     // that temporary.
1871     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
1872     EmitAnyExprToMem(E, V, false, false);
1873     return MakeAddrLValue(V, E->getType());
1874   }
1875
1876   case CK_Dynamic: {
1877     LValue LV = EmitLValue(E->getSubExpr());
1878     llvm::Value *V = LV.getAddress();
1879     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1880     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
1881   }
1882
1883   case CK_ConstructorConversion:
1884   case CK_UserDefinedConversion:
1885   case CK_AnyPointerToObjCPointerCast:
1886     return EmitLValue(E->getSubExpr());
1887   
1888   case CK_UncheckedDerivedToBase:
1889   case CK_DerivedToBase: {
1890     const RecordType *DerivedClassTy = 
1891       E->getSubExpr()->getType()->getAs<RecordType>();
1892     CXXRecordDecl *DerivedClassDecl = 
1893       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1894     
1895     LValue LV = EmitLValue(E->getSubExpr());
1896     llvm::Value *This = LV.getAddress();
1897     
1898     // Perform the derived-to-base conversion
1899     llvm::Value *Base = 
1900       GetAddressOfBaseClass(This, DerivedClassDecl, 
1901                             E->path_begin(), E->path_end(),
1902                             /*NullCheckValue=*/false);
1903     
1904     return MakeAddrLValue(Base, E->getType());
1905   }
1906   case CK_ToUnion:
1907     return EmitAggExprToLValue(E);
1908   case CK_BaseToDerived: {
1909     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
1910     CXXRecordDecl *DerivedClassDecl = 
1911       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1912     
1913     LValue LV = EmitLValue(E->getSubExpr());
1914     
1915     // Perform the base-to-derived conversion
1916     llvm::Value *Derived = 
1917       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 
1918                                E->path_begin(), E->path_end(),
1919                                /*NullCheckValue=*/false);
1920     
1921     return MakeAddrLValue(Derived, E->getType());
1922   }
1923   case CK_LValueBitCast: {
1924     // This must be a reinterpret_cast (or c-style equivalent).
1925     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1926     
1927     LValue LV = EmitLValue(E->getSubExpr());
1928     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1929                                            ConvertType(CE->getTypeAsWritten()));
1930     return MakeAddrLValue(V, E->getType());
1931   }
1932   case CK_ObjCObjectLValueCast: {
1933     LValue LV = EmitLValue(E->getSubExpr());
1934     QualType ToType = getContext().getLValueReferenceType(E->getType());
1935     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 
1936                                            ConvertType(ToType));
1937     return MakeAddrLValue(V, E->getType());
1938   }
1939   }
1940   
1941   llvm_unreachable("Unhandled lvalue cast kind?");
1942 }
1943
1944 LValue CodeGenFunction::EmitNullInitializationLValue(
1945                                               const CXXScalarValueInitExpr *E) {
1946   QualType Ty = E->getType();
1947   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
1948   EmitNullInitialization(LV.getAddress(), Ty);
1949   return LV;
1950 }
1951
1952 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
1953   assert(e->isGLValue() || e->getType()->isRecordType());
1954   return getOpaqueLValueMapping(e);
1955 }
1956
1957 //===--------------------------------------------------------------------===//
1958 //                             Expression Emission
1959 //===--------------------------------------------------------------------===//
1960
1961
1962 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 
1963                                      ReturnValueSlot ReturnValue) {
1964   if (CGDebugInfo *DI = getDebugInfo()) {
1965     DI->setLocation(E->getLocStart());
1966     DI->UpdateLineDirectiveRegion(Builder);
1967     DI->EmitStopPoint(Builder);
1968   }
1969
1970   // Builtins never have block type.
1971   if (E->getCallee()->getType()->isBlockPointerType())
1972     return EmitBlockCallExpr(E, ReturnValue);
1973
1974   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1975     return EmitCXXMemberCallExpr(CE, ReturnValue);
1976
1977   const Decl *TargetDecl = 0;
1978   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1979     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1980       TargetDecl = DRE->getDecl();
1981       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1982         if (unsigned builtinID = FD->getBuiltinID())
1983           return EmitBuiltinExpr(FD, builtinID, E);
1984     }
1985   }
1986
1987   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1988     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1989       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
1990
1991   if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
1992     // C++ [expr.pseudo]p1:
1993     //   The result shall only be used as the operand for the function call
1994     //   operator (), and the result of such a call has type void. The only
1995     //   effect is the evaluation of the postfix-expression before the dot or
1996     //   arrow.
1997     EmitScalarExpr(E->getCallee());
1998     return RValue::get(0);
1999   }
2000
2001   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
2002   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
2003                   E->arg_begin(), E->arg_end(), TargetDecl);
2004 }
2005
2006 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2007   // Comma expressions just emit their LHS then their RHS as an l-value.
2008   if (E->getOpcode() == BO_Comma) {
2009     EmitIgnoredExpr(E->getLHS());
2010     EnsureInsertPoint();
2011     return EmitLValue(E->getRHS());
2012   }
2013
2014   if (E->getOpcode() == BO_PtrMemD ||
2015       E->getOpcode() == BO_PtrMemI)
2016     return EmitPointerToDataMemberBinaryExpr(E);
2017
2018   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2019   
2020   if (!hasAggregateLLVMType(E->getType())) {
2021     // __block variables need the RHS evaluated first.
2022     RValue RV = EmitAnyExpr(E->getRHS());
2023     LValue LV = EmitLValue(E->getLHS());
2024     EmitStoreThroughLValue(RV, LV, E->getType());
2025     return LV;
2026   }
2027
2028   if (E->getType()->isAnyComplexType())
2029     return EmitComplexAssignmentLValue(E);
2030
2031   return EmitAggExprToLValue(E);
2032 }
2033
2034 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2035   RValue RV = EmitCallExpr(E);
2036
2037   if (!RV.isScalar())
2038     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2039     
2040   assert(E->getCallReturnType()->isReferenceType() &&
2041          "Can't have a scalar return unless the return type is a "
2042          "reference type!");
2043
2044   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2045 }
2046
2047 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2048   // FIXME: This shouldn't require another copy.
2049   return EmitAggExprToLValue(E);
2050 }
2051
2052 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2053   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2054          && "binding l-value to type which needs a temporary");
2055   AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp");
2056   EmitCXXConstructExpr(E, Slot);
2057   return MakeAddrLValue(Slot.getAddr(), E->getType());
2058 }
2059
2060 LValue
2061 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2062   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2063 }
2064
2065 LValue
2066 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2067   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2068   Slot.setLifetimeExternallyManaged();
2069   EmitAggExpr(E->getSubExpr(), Slot);
2070   EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
2071   return MakeAddrLValue(Slot.getAddr(), E->getType());
2072 }
2073
2074 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2075   RValue RV = EmitObjCMessageExpr(E);
2076   
2077   if (!RV.isScalar())
2078     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2079   
2080   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2081          "Can't have a scalar return unless the return type is a "
2082          "reference type!");
2083   
2084   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2085 }
2086
2087 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2088   llvm::Value *V = 
2089     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2090   return MakeAddrLValue(V, E->getType());
2091 }
2092
2093 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2094                                              const ObjCIvarDecl *Ivar) {
2095   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2096 }
2097
2098 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2099                                           llvm::Value *BaseValue,
2100                                           const ObjCIvarDecl *Ivar,
2101                                           unsigned CVRQualifiers) {
2102   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2103                                                    Ivar, CVRQualifiers);
2104 }
2105
2106 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2107   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2108   llvm::Value *BaseValue = 0;
2109   const Expr *BaseExpr = E->getBase();
2110   Qualifiers BaseQuals;
2111   QualType ObjectTy;
2112   if (E->isArrow()) {
2113     BaseValue = EmitScalarExpr(BaseExpr);
2114     ObjectTy = BaseExpr->getType()->getPointeeType();
2115     BaseQuals = ObjectTy.getQualifiers();
2116   } else {
2117     LValue BaseLV = EmitLValue(BaseExpr);
2118     // FIXME: this isn't right for bitfields.
2119     BaseValue = BaseLV.getAddress();
2120     ObjectTy = BaseExpr->getType();
2121     BaseQuals = ObjectTy.getQualifiers();
2122   }
2123
2124   LValue LV = 
2125     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2126                       BaseQuals.getCVRQualifiers());
2127   setObjCGCLValueClass(getContext(), E, LV);
2128   return LV;
2129 }
2130
2131 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2132   // Can only get l-value for message expression returning aggregate type
2133   RValue RV = EmitAnyExprToTemp(E);
2134   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2135 }
2136
2137 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2138                                  ReturnValueSlot ReturnValue,
2139                                  CallExpr::const_arg_iterator ArgBeg,
2140                                  CallExpr::const_arg_iterator ArgEnd,
2141                                  const Decl *TargetDecl) {
2142   // Get the actual function type. The callee type will always be a pointer to
2143   // function type or a block pointer type.
2144   assert(CalleeType->isFunctionPointerType() &&
2145          "Call must have function pointer type!");
2146
2147   CalleeType = getContext().getCanonicalType(CalleeType);
2148
2149   const FunctionType *FnType
2150     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2151
2152   CallArgList Args;
2153   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2154
2155   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2156                   Callee, ReturnValue, Args, TargetDecl);
2157 }
2158
2159 LValue CodeGenFunction::
2160 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2161   llvm::Value *BaseV;
2162   if (E->getOpcode() == BO_PtrMemI)
2163     BaseV = EmitScalarExpr(E->getLHS());
2164   else
2165     BaseV = EmitLValue(E->getLHS()).getAddress();
2166
2167   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2168
2169   const MemberPointerType *MPT
2170     = E->getRHS()->getType()->getAs<MemberPointerType>();
2171
2172   llvm::Value *AddV =
2173     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2174
2175   return MakeAddrLValue(AddV, MPT->getPointeeType());
2176 }