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 "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "llvm/Target/TargetData.h"
20 using namespace clang;
21 using namespace CodeGen;
22 
23 //===--------------------------------------------------------------------===//
24 //                        Miscellaneous Helper Methods
25 //===--------------------------------------------------------------------===//
26 
27 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
28 /// block.
29 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
30                                                     const char *Name) {
31   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
32 }
33 
34 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
35 /// expression and compare the result against zero, returning an Int1Ty value.
36 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
37   QualType BoolTy = getContext().BoolTy;
38   if (!E->getType()->isAnyComplexType())
39     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
40 
41   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
42 }
43 
44 /// EmitAnyExpr - Emit code to compute the specified expression which can have
45 /// any type.  The result is returned as an RValue struct.  If this is an
46 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
47 /// the result should be returned.
48 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
49                                     bool isAggLocVolatile) {
50   if (!hasAggregateLLVMType(E->getType()))
51     return RValue::get(EmitScalarExpr(E));
52   else if (E->getType()->isAnyComplexType())
53     return RValue::getComplex(EmitComplexExpr(E));
54 
55   EmitAggExpr(E, AggLoc, isAggLocVolatile);
56   return RValue::getAggregate(AggLoc);
57 }
58 
59 /// getAccessedFieldNo - Given an encoded value and a result number, return
60 /// the input field number being accessed.
61 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
62                                              const llvm::Constant *Elts) {
63   if (isa<llvm::ConstantAggregateZero>(Elts))
64     return 0;
65 
66   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
67 }
68 
69 
70 //===----------------------------------------------------------------------===//
71 //                         LValue Expression Emission
72 //===----------------------------------------------------------------------===//
73 
74 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
75                                               const char *Name) {
76   ErrorUnsupported(E, Name);
77   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
78   return LValue::MakeAddr(llvm::UndefValue::get(Ty),
79                           E->getType().getCVRQualifiers());
80 }
81 
82 /// EmitLValue - Emit code to compute a designator that specifies the location
83 /// of the expression.
84 ///
85 /// This can return one of two things: a simple address or a bitfield
86 /// reference.  In either case, the LLVM Value* in the LValue structure is
87 /// guaranteed to be an LLVM pointer type.
88 ///
89 /// If this returns a bitfield reference, nothing about the pointee type of
90 /// the LLVM value is known: For example, it may not be a pointer to an
91 /// integer.
92 ///
93 /// If this returns a normal address, and if the lvalue's C type is fixed
94 /// size, this method guarantees that the returned pointer type will point to
95 /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
96 /// variable length type, this is not possible.
97 ///
98 LValue CodeGenFunction::EmitLValue(const Expr *E) {
99   switch (E->getStmtClass()) {
100   default: return EmitUnsupportedLValue(E, "l-value expression");
101 
102   case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E));
103   case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
104   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
105   case Expr::PredefinedExprClass:
106     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
107   case Expr::StringLiteralClass:
108     return EmitStringLiteralLValue(cast<StringLiteral>(E));
109 
110   case Expr::ObjCMessageExprClass:
111     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
112   case Expr::ObjCIvarRefExprClass:
113     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
114   case Expr::ObjCPropertyRefExprClass:
115     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
116 
117   case Expr::UnaryOperatorClass:
118     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
119   case Expr::ArraySubscriptExprClass:
120     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
121   case Expr::ExtVectorElementExprClass:
122     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
123   case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
124   case Expr::CompoundLiteralExprClass:
125     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
126   }
127 }
128 
129 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
130 /// this method emits the address of the lvalue, then loads the result as an
131 /// rvalue, returning the rvalue.
132 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
133   if (LV.isSimple()) {
134     llvm::Value *Ptr = LV.getAddress();
135     const llvm::Type *EltTy =
136       cast<llvm::PointerType>(Ptr->getType())->getElementType();
137 
138     // Simple scalar l-value.
139     if (EltTy->isSingleValueType()) {
140       llvm::Value *V = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),"tmp");
141 
142       // Bool can have different representation in memory than in registers.
143       if (ExprType->isBooleanType()) {
144         if (V->getType() != llvm::Type::Int1Ty)
145           V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
146       }
147 
148       return RValue::get(V);
149     }
150 
151     assert(ExprType->isFunctionType() && "Unknown scalar value");
152     return RValue::get(Ptr);
153   }
154 
155   if (LV.isVectorElt()) {
156     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
157                                           LV.isVolatileQualified(), "tmp");
158     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
159                                                     "vecext"));
160   }
161 
162   // If this is a reference to a subset of the elements of a vector, either
163   // shuffle the input or extract/insert them as appropriate.
164   if (LV.isExtVectorElt())
165     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
166 
167   if (LV.isBitfield())
168     return EmitLoadOfBitfieldLValue(LV, ExprType);
169 
170   if (LV.isPropertyRef())
171     return EmitLoadOfPropertyRefLValue(LV, ExprType);
172 
173   assert(0 && "Unknown LValue type!");
174   //an invalid RValue, but the assert will
175   //ensure that this point is never reached
176   return RValue();
177 }
178 
179 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
180                                                  QualType ExprType) {
181   unsigned StartBit = LV.getBitfieldStartBit();
182   unsigned BitfieldSize = LV.getBitfieldSize();
183   llvm::Value *Ptr = LV.getBitfieldAddr();
184 
185   const llvm::Type *EltTy =
186     cast<llvm::PointerType>(Ptr->getType())->getElementType();
187   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
188 
189   // In some cases the bitfield may straddle two memory locations.
190   // Currently we load the entire bitfield, then do the magic to
191   // sign-extend it if necessary. This results in somewhat more code
192   // than necessary for the common case (one load), since two shifts
193   // accomplish both the masking and sign extension.
194   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
195   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
196 
197   // Shift to proper location.
198   Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
199                            "bf.lo");
200 
201   // Mask off unused bits.
202   llvm::Constant *LowMask =
203     llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, LowBits));
204   Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
205 
206   // Fetch the high bits if necessary.
207   if (LowBits < BitfieldSize) {
208     unsigned HighBits = BitfieldSize - LowBits;
209     llvm::Value *HighPtr =
210       Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1),
211                         "bf.ptr.hi");
212     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
213                                               LV.isVolatileQualified(),
214                                               "tmp");
215 
216     // Mask off unused bits.
217     llvm::Constant *HighMask =
218       llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, HighBits));
219     HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
220 
221     // Shift to proper location and or in to bitfield value.
222     HighVal = Builder.CreateShl(HighVal,
223                                 llvm::ConstantInt::get(EltTy, LowBits));
224     Val = Builder.CreateOr(Val, HighVal, "bf.val");
225   }
226 
227   // Sign extend if necessary.
228   if (LV.isBitfieldSigned()) {
229     llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
230                                                     EltTySize - BitfieldSize);
231     Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
232                              ExtraBits, "bf.val.sext");
233   }
234 
235   // The bitfield type and the normal type differ when the storage sizes
236   // differ (currently just _Bool).
237   Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
238 
239   return RValue::get(Val);
240 }
241 
242 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
243                                                     QualType ExprType) {
244   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
245 }
246 
247 // If this is a reference to a subset of the elements of a vector, either
248 // shuffle the input or extract/insert them as appropriate.
249 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
250                                                          QualType ExprType) {
251   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
252                                         LV.isVolatileQualified(), "tmp");
253 
254   const llvm::Constant *Elts = LV.getExtVectorElts();
255 
256   // If the result of the expression is a non-vector type, we must be
257   // extracting a single element.  Just codegen as an extractelement.
258   const VectorType *ExprVT = ExprType->getAsVectorType();
259   if (!ExprVT) {
260     unsigned InIdx = getAccessedFieldNo(0, Elts);
261     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
262     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
263   }
264 
265   // If the source and destination have the same number of elements, use a
266   // vector shuffle instead of insert/extracts.
267   unsigned NumResultElts = ExprVT->getNumElements();
268   unsigned NumSourceElts =
269     cast<llvm::VectorType>(Vec->getType())->getNumElements();
270 
271   if (NumResultElts == NumSourceElts) {
272     llvm::SmallVector<llvm::Constant*, 4> Mask;
273     for (unsigned i = 0; i != NumResultElts; ++i) {
274       unsigned InIdx = getAccessedFieldNo(i, Elts);
275       Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
276     }
277 
278     llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
279     Vec = Builder.CreateShuffleVector(Vec,
280                                       llvm::UndefValue::get(Vec->getType()),
281                                       MaskV, "tmp");
282     return RValue::get(Vec);
283   }
284 
285   // Start out with an undef of the result type.
286   llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
287 
288   // Extract/Insert each element of the result.
289   for (unsigned i = 0; i != NumResultElts; ++i) {
290     unsigned InIdx = getAccessedFieldNo(i, Elts);
291     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
292     Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
293 
294     llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
295     Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
296   }
297 
298   return RValue::get(Result);
299 }
300 
301 
302 
303 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
304 /// lvalue, where both are guaranteed to the have the same type, and that type
305 /// is 'Ty'.
306 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
307                                              QualType Ty) {
308   if (!Dst.isSimple()) {
309     if (Dst.isVectorElt()) {
310       // Read/modify/write the vector, inserting the new element.
311       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
312                                             Dst.isVolatileQualified(), "tmp");
313       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
314                                         Dst.getVectorIdx(), "vecins");
315       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
316       return;
317     }
318 
319     // If this is an update of extended vector elements, insert them as
320     // appropriate.
321     if (Dst.isExtVectorElt())
322       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
323 
324     if (Dst.isBitfield())
325       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
326 
327     if (Dst.isPropertyRef())
328       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
329 
330     assert(0 && "Unknown LValue type");
331   }
332 
333   llvm::Value *DstAddr = Dst.getAddress();
334   assert(Src.isScalar() && "Can't emit an agg store with this method");
335   // FIXME: Handle volatility etc.
336   const llvm::Type *SrcTy = Src.getScalarVal()->getType();
337   const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
338   const llvm::Type *AddrTy = DstPtr->getElementType();
339   unsigned AS = DstPtr->getAddressSpace();
340 
341   if (AddrTy != SrcTy)
342     DstAddr = Builder.CreateBitCast(DstAddr,
343                                     llvm::PointerType::get(SrcTy, AS),
344                                     "storetmp");
345   Builder.CreateStore(Src.getScalarVal(), DstAddr, Dst.isVolatileQualified());
346 }
347 
348 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
349                                                      QualType Ty) {
350   unsigned StartBit = Dst.getBitfieldStartBit();
351   unsigned BitfieldSize = Dst.getBitfieldSize();
352   llvm::Value *Ptr = Dst.getBitfieldAddr();
353 
354   const llvm::Type *EltTy =
355     cast<llvm::PointerType>(Ptr->getType())->getElementType();
356   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
357 
358   // Get the new value, cast to the appropriate type and masked to
359   // exactly the size of the bit-field.
360   llvm::Value *NewVal = Src.getScalarVal();
361   NewVal = Builder.CreateIntCast(NewVal, EltTy, false, "tmp");
362   llvm::Constant *Mask =
363     llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
364   NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
365 
366   // In some cases the bitfield may straddle two memory locations.
367   // Emit the low part first and check to see if the high needs to be
368   // done.
369   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
370   llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
371                                            "bf.prev.low");
372 
373   // Compute the mask for zero-ing the low part of this bitfield.
374   llvm::Constant *InvMask =
375     llvm::ConstantInt::get(~llvm::APInt::getBitsSet(EltTySize, StartBit,
376                                                     StartBit + LowBits));
377 
378   // Compute the new low part as
379   //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
380   // with the shift of NewVal implicitly stripping the high bits.
381   llvm::Value *NewLowVal =
382     Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
383                       "bf.value.lo");
384   LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
385   LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
386 
387   // Write back.
388   Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
389 
390   // If the low part doesn't cover the bitfield emit a high part.
391   if (LowBits < BitfieldSize) {
392     unsigned HighBits = BitfieldSize - LowBits;
393     llvm::Value *HighPtr =
394       Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1),
395                         "bf.ptr.hi");
396     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
397                                               Dst.isVolatileQualified(),
398                                               "bf.prev.hi");
399 
400     // Compute the mask for zero-ing the high part of this bitfield.
401     llvm::Constant *InvMask =
402       llvm::ConstantInt::get(~llvm::APInt::getLowBitsSet(EltTySize, HighBits));
403 
404     // Compute the new high part as
405     //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
406     // where the high bits of NewVal have already been cleared and the
407     // shift stripping the low bits.
408     llvm::Value *NewHighVal =
409       Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
410                         "bf.value.high");
411     HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
412     HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
413 
414     // Write back.
415     Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
416   }
417 }
418 
419 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
420                                                         LValue Dst,
421                                                         QualType Ty) {
422   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
423 }
424 
425 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
426                                                                LValue Dst,
427                                                                QualType Ty) {
428   // This access turns into a read/modify/write of the vector.  Load the input
429   // value now.
430   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
431                                         Dst.isVolatileQualified(), "tmp");
432   const llvm::Constant *Elts = Dst.getExtVectorElts();
433 
434   llvm::Value *SrcVal = Src.getScalarVal();
435 
436   if (const VectorType *VTy = Ty->getAsVectorType()) {
437     unsigned NumSrcElts = VTy->getNumElements();
438 
439     // Extract/Insert each element.
440     for (unsigned i = 0; i != NumSrcElts; ++i) {
441       llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
442       Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
443 
444       unsigned Idx = getAccessedFieldNo(i, Elts);
445       llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
446       Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
447     }
448   } else {
449     // If the Src is a scalar (not a vector) it must be updating one element.
450     unsigned InIdx = getAccessedFieldNo(0, Elts);
451     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
452     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
453   }
454 
455   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
456 }
457 
458 
459 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
460   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
461 
462   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) ||
463         isa<ImplicitParamDecl>(VD))) {
464     if (VD->getStorageClass() == VarDecl::Extern)
465       return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD),
466                               E->getType().getCVRQualifiers());
467     else {
468       llvm::Value *V = LocalDeclMap[VD];
469       assert(V && "BlockVarDecl not entered in LocalDeclMap?");
470       return LValue::MakeAddr(V, E->getType().getCVRQualifiers());
471     }
472   } else if (VD && VD->isFileVarDecl()) {
473     return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD),
474                             E->getType().getCVRQualifiers());
475   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
476     return LValue::MakeAddr(CGM.GetAddrOfFunction(FD),
477                             E->getType().getCVRQualifiers());
478   }
479   else if (const ImplicitParamDecl *IPD =
480       dyn_cast<ImplicitParamDecl>(E->getDecl())) {
481     llvm::Value *V = LocalDeclMap[IPD];
482     assert(V && "BlockVarDecl not entered in LocalDeclMap?");
483     return LValue::MakeAddr(V, E->getType().getCVRQualifiers());
484   }
485   assert(0 && "Unimp declref");
486   //an invalid LValue, but the assert will
487   //ensure that this point is never reached.
488   return LValue();
489 }
490 
491 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
492   // __extension__ doesn't affect lvalue-ness.
493   if (E->getOpcode() == UnaryOperator::Extension)
494     return EmitLValue(E->getSubExpr());
495 
496   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
497   switch (E->getOpcode()) {
498   default: assert(0 && "Unknown unary operator lvalue!");
499   case UnaryOperator::Deref:
500     return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()),
501                             ExprTy->getAsPointerType()->getPointeeType()
502                                     .getCVRQualifiers());
503   case UnaryOperator::Real:
504   case UnaryOperator::Imag:
505     LValue LV = EmitLValue(E->getSubExpr());
506     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
507     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
508                                                     Idx, "idx"),
509                             ExprTy.getCVRQualifiers());
510   }
511 }
512 
513 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
514   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0);
515 }
516 
517 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
518   std::string FunctionName;
519   if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
520     FunctionName = FD->getName();
521   } else if (isa<ObjCMethodDecl>(CurFuncDecl)) {
522     // Just get the mangled name.
523     FunctionName  = CurFn->getName();
524   } else {
525     return EmitUnsupportedLValue(E, "predefined expression");
526   }
527   std::string GlobalVarName;
528 
529   switch (E->getIdentType()) {
530     default:
531       return EmitUnsupportedLValue(E, "predefined expression");
532     case PredefinedExpr::Func:
533       GlobalVarName = "__func__.";
534       break;
535     case PredefinedExpr::Function:
536       GlobalVarName = "__FUNCTION__.";
537       break;
538     case PredefinedExpr::PrettyFunction:
539       // FIXME:: Demangle C++ method names
540       GlobalVarName = "__PRETTY_FUNCTION__.";
541       break;
542   }
543 
544   GlobalVarName += FunctionName;
545 
546   // FIXME: Can cache/reuse these within the module.
547   llvm::Constant *C = llvm::ConstantArray::get(FunctionName);
548 
549   // Create a global variable for this.
550   C = new llvm::GlobalVariable(C->getType(), true,
551                                llvm::GlobalValue::InternalLinkage,
552                                C, GlobalVarName, CurFn->getParent());
553   return LValue::MakeAddr(C,0);
554 }
555 
556 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
557   // The index must always be an integer, which is not an aggregate.  Emit it.
558   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
559 
560   // If the base is a vector type, then we are forming a vector element lvalue
561   // with this subscript.
562   if (E->getBase()->getType()->isVectorType()) {
563     // Emit the vector as an lvalue to get its address.
564     LValue LHS = EmitLValue(E->getBase());
565     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
566     // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
567     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
568       E->getBase()->getType().getCVRQualifiers());
569   }
570 
571   // The base must be a pointer, which is not an aggregate.  Emit it.
572   llvm::Value *Base = EmitScalarExpr(E->getBase());
573 
574   // Extend or truncate the index type to 32 or 64-bits.
575   QualType IdxTy  = E->getIdx()->getType();
576   bool IdxSigned = IdxTy->isSignedIntegerType();
577   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
578   if (IdxBitwidth != LLVMPointerWidth)
579     Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
580                                 IdxSigned, "idxprom");
581 
582   // We know that the pointer points to a type of the correct size, unless the
583   // size is a VLA.
584   if (!E->getType()->isConstantSizeType())
585     return EmitUnsupportedLValue(E, "VLA index");
586   QualType ExprTy = getContext().getCanonicalType(E->getBase()->getType());
587 
588   return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"),
589                           ExprTy->getAsPointerType()->getPointeeType()
590                                .getCVRQualifiers());
591 }
592 
593 static
594 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) {
595   llvm::SmallVector<llvm::Constant *, 4> CElts;
596 
597   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
598     CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i]));
599 
600   return llvm::ConstantVector::get(&CElts[0], CElts.size());
601 }
602 
603 LValue CodeGenFunction::
604 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
605   // Emit the base vector as an l-value.
606   LValue Base = EmitLValue(E->getBase());
607 
608   // Encode the element access list into a vector of unsigned indices.
609   llvm::SmallVector<unsigned, 4> Indices;
610   E->getEncodedElementAccess(Indices);
611 
612   if (Base.isSimple()) {
613     llvm::Constant *CV = GenerateConstantVector(Indices);
614     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
615                                    E->getBase()->getType().getCVRQualifiers());
616   }
617   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
618 
619   llvm::Constant *BaseElts = Base.getExtVectorElts();
620   llvm::SmallVector<llvm::Constant *, 4> CElts;
621 
622   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
623     if (isa<llvm::ConstantAggregateZero>(BaseElts))
624       CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
625     else
626       CElts.push_back(BaseElts->getOperand(Indices[i]));
627   }
628   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
629   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
630                                   E->getBase()->getType().getCVRQualifiers());
631 }
632 
633 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
634   bool isUnion = false;
635   Expr *BaseExpr = E->getBase();
636   llvm::Value *BaseValue = NULL;
637   unsigned CVRQualifiers=0;
638 
639   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
640   if (E->isArrow()) {
641     BaseValue = EmitScalarExpr(BaseExpr);
642     const PointerType *PTy =
643       cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType()));
644     if (PTy->getPointeeType()->isUnionType())
645       isUnion = true;
646     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
647   }
648   else {
649     LValue BaseLV = EmitLValue(BaseExpr);
650     // FIXME: this isn't right for bitfields.
651     BaseValue = BaseLV.getAddress();
652     if (BaseExpr->getType()->isUnionType())
653       isUnion = true;
654     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
655   }
656 
657   FieldDecl *Field = E->getMemberDecl();
658   return EmitLValueForField(BaseValue, Field, isUnion, CVRQualifiers);
659 }
660 
661 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
662                                            FieldDecl* Field,
663                                            bool isUnion,
664                                            unsigned CVRQualifiers)
665 {
666   llvm::Value *V;
667   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
668 
669   if (Field->isBitField()) {
670     // FIXME: CodeGenTypes should expose a method to get the appropriate
671     // type for FieldTy (the appropriate type is ABI-dependent).
672     const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType());
673     const llvm::PointerType *BaseTy =
674       cast<llvm::PointerType>(BaseValue->getType());
675     unsigned AS = BaseTy->getAddressSpace();
676     BaseValue = Builder.CreateBitCast(BaseValue,
677                                       llvm::PointerType::get(FieldTy, AS),
678                                       "tmp");
679     V = Builder.CreateGEP(BaseValue,
680                           llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
681                           "tmp");
682 
683     CodeGenTypes::BitFieldInfo bitFieldInfo =
684       CGM.getTypes().getBitFieldInfo(Field);
685     return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
686                                 Field->getType()->isSignedIntegerType(),
687                             Field->getType().getCVRQualifiers()|CVRQualifiers);
688   }
689 
690   V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
691 
692   // Match union field type.
693   if (isUnion) {
694     const llvm::Type *FieldTy =
695       CGM.getTypes().ConvertTypeForMem(Field->getType());
696     const llvm::PointerType * BaseTy =
697       cast<llvm::PointerType>(BaseValue->getType());
698     unsigned AS = BaseTy->getAddressSpace();
699     V = Builder.CreateBitCast(V,
700                               llvm::PointerType::get(FieldTy, AS),
701                               "tmp");
702   }
703 
704   return LValue::MakeAddr(V,
705                           Field->getType().getCVRQualifiers()|CVRQualifiers);
706 }
707 
708 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E)
709 {
710   const llvm::Type *LTy = ConvertType(E->getType());
711   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
712 
713   const Expr* InitExpr = E->getInitializer();
714   LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers());
715 
716   if (E->getType()->isComplexType()) {
717     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
718   } else if (hasAggregateLLVMType(E->getType())) {
719     EmitAnyExpr(InitExpr, DeclPtr, false);
720   } else {
721     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
722   }
723 
724   return Result;
725 }
726 
727 //===--------------------------------------------------------------------===//
728 //                             Expression Emission
729 //===--------------------------------------------------------------------===//
730 
731 
732 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
733   if (const ImplicitCastExpr *IcExpr =
734       dyn_cast<const ImplicitCastExpr>(E->getCallee()))
735     if (const DeclRefExpr *DRExpr =
736         dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
737       if (const FunctionDecl *FDecl =
738           dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
739         if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
740           return EmitBuiltinExpr(builtinID, E);
741 
742   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
743   return EmitCallExpr(Callee, E->getCallee()->getType(),
744                       E->arg_begin(), E->arg_end());
745 }
746 
747 RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr,
748                                      CallExpr::const_arg_iterator ArgBeg,
749                                      CallExpr::const_arg_iterator ArgEnd) {
750 
751   llvm::Value *Callee = EmitScalarExpr(FnExpr);
752   return EmitCallExpr(Callee, FnExpr->getType(), ArgBeg, ArgEnd);
753 }
754 
755 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
756   // Can only get l-value for call expression returning aggregate type
757   RValue RV = EmitCallExpr(E);
758   // FIXME: can this be volatile?
759   return LValue::MakeAddr(RV.getAggregateAddr(),
760                           E->getType().getCVRQualifiers());
761 }
762 
763 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
764   // Can only get l-value for message expression returning aggregate type
765   RValue RV = EmitObjCMessageExpr(E);
766   // FIXME: can this be volatile?
767   return LValue::MakeAddr(RV.getAggregateAddr(),
768                           E->getType().getCVRQualifiers());
769 }
770 
771 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
772   // Objective-C objects are traditionally C structures with their layout
773   // defined at compile-time.  In some implementations, their layout is not
774   // defined until run time in order to allow instance variables to be added to
775   // a class without recompiling all of the subclasses.  If this is the case
776   // then the CGObjCRuntime subclass must return true to LateBoundIvars and
777   // implement the lookup itself.
778   if (CGM.getObjCRuntime().LateBoundIVars()) {
779     return EmitUnsupportedLValue(E, "late-bound instance variables");
780   }
781 
782   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
783   llvm::Value *BaseValue = 0;
784   const Expr *BaseExpr = E->getBase();
785   unsigned CVRQualifiers = 0;
786   if (E->isArrow()) {
787     BaseValue = EmitScalarExpr(BaseExpr);
788     const PointerType *PTy =
789       cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType()));
790     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
791   } else {
792     LValue BaseLV = EmitLValue(BaseExpr);
793     // FIXME: this isn't right for bitfields.
794     BaseValue = BaseLV.getAddress();
795     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
796   }
797 
798   const ObjCIvarDecl *Field = E->getDecl();
799   if (Field->isBitField())
800     return EmitUnsupportedLValue(E, "ivar bitfields");
801 
802   // TODO:  Add a special case for isa (index 0)
803   unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
804 
805   llvm::Value *V = Builder.CreateStructGEP(BaseValue, Index, "tmp");
806   return LValue::MakeAddr(V,
807                           Field->getType().getCVRQualifiers()|CVRQualifiers);
808 }
809 
810 LValue
811 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
812   // This is a special l-value that just issues sends when we load or
813   // store through it.
814   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
815 }
816 
817 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType,
818                                      CallExpr::const_arg_iterator ArgBeg,
819                                      CallExpr::const_arg_iterator ArgEnd) {
820 
821   // The callee type will always be a pointer to function type, get the function
822   // type.
823   FnType = FnType->getAsPointerType()->getPointeeType();
824   QualType ResultType = FnType->getAsFunctionType()->getResultType();
825 
826   CallArgList Args;
827   for (CallExpr::const_arg_iterator I = ArgBeg; I != ArgEnd; ++I)
828     EmitCallArg(*I, Args);
829 
830   return EmitCall(Callee, ResultType, Args);
831 }
832 
833 // FIXME: Merge the following two functions.
834 void CodeGenFunction::EmitCallArg(RValue RV, QualType Ty,
835                                   CallArgList &Args) {
836   llvm::Value *ArgValue;
837 
838   if (RV.isScalar()) {
839     ArgValue = RV.getScalarVal();
840   } else if (RV.isComplex()) {
841     // Make a temporary alloca to pass the argument.
842     ArgValue = CreateTempAlloca(ConvertType(Ty));
843     StoreComplexToAddr(RV.getComplexVal(), ArgValue, false);
844   } else {
845     ArgValue = RV.getAggregateAddr();
846   }
847 
848   Args.push_back(std::make_pair(ArgValue, Ty));
849 }
850 
851 void CodeGenFunction::EmitCallArg(const Expr *E, CallArgList &Args) {
852   QualType ArgTy = E->getType();
853   llvm::Value *ArgValue;
854 
855   if (!hasAggregateLLVMType(ArgTy)) {
856     // Scalar argument is passed by-value.
857     ArgValue = EmitScalarExpr(E);
858   } else if (ArgTy->isAnyComplexType()) {
859     // Make a temporary alloca to pass the argument.
860     ArgValue = CreateTempAlloca(ConvertType(ArgTy));
861     EmitComplexExprIntoAddr(E, ArgValue, false);
862   } else {
863     ArgValue = CreateTempAlloca(ConvertType(ArgTy));
864     EmitAggExpr(E, ArgValue, false);
865   }
866 
867   Args.push_back(std::make_pair(ArgValue, E->getType()));
868 }
869 
870 RValue CodeGenFunction::EmitCall(llvm::Value *Callee,
871                                  QualType ResultType,
872                                  const CallArgList &CallArgs) {
873   llvm::SmallVector<llvm::Value*, 16> Args;
874   llvm::Value *TempArg0 = 0;
875 
876   // Handle struct-return functions by passing a pointer to the location that
877   // we would like to return into.
878   if (hasAggregateLLVMType(ResultType)) {
879     // Create a temporary alloca to hold the result of the call. :(
880     TempArg0 = CreateTempAlloca(ConvertType(ResultType));
881     Args.push_back(TempArg0);
882   }
883 
884   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
885        I != E; ++I)
886     Args.push_back(I->first);
887 
888   llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size());
889 
890   // Note that there is parallel code in SetFunctionAttributes in CodeGenModule
891   llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
892   unsigned Index = 1;
893   if (TempArg0) {
894     ParamAttrList.push_back(
895         llvm::ParamAttrsWithIndex::get(Index, llvm::ParamAttr::StructRet));
896     ++Index;
897   }
898 
899   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
900        I != E; ++I, ++Index) {
901     QualType ParamType = I->second;
902     unsigned ParamAttrs = 0;
903     if (ParamType->isRecordType())
904       ParamAttrs |= llvm::ParamAttr::ByVal;
905     if (ParamType->isPromotableIntegerType()) {
906       if (ParamType->isSignedIntegerType()) {
907         ParamAttrs |= llvm::ParamAttr::SExt;
908       } else if (ParamType->isUnsignedIntegerType()) {
909         ParamAttrs |= llvm::ParamAttr::ZExt;
910       }
911     }
912     if (ParamAttrs)
913       ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(Index,
914                                                              ParamAttrs));
915   }
916   CI->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
917                                          ParamAttrList.size()));
918 
919   if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
920     CI->setCallingConv(F->getCallingConv());
921   if (CI->getType() != llvm::Type::VoidTy)
922     CI->setName("call");
923   else if (ResultType->isAnyComplexType())
924     return RValue::getComplex(LoadComplexFromAddr(TempArg0, false));
925   else if (hasAggregateLLVMType(ResultType))
926     // Struct return.
927     return RValue::getAggregate(TempArg0);
928   else {
929     // void return.
930     assert(ResultType->isVoidType() && "Should only have a void expr here");
931     CI = 0;
932   }
933 
934   return RValue::get(CI);
935 }
936