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