1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant 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 Constant Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/Basic/Builtins.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Target/TargetData.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 namespace  {
31 
32 class VISIBILITY_HIDDEN ConstStructBuilder {
33   CodeGenModule &CGM;
34   CodeGenFunction *CGF;
35 
36   bool Packed;
37 
38   unsigned NextFieldOffsetInBytes;
39 
40   unsigned LLVMStructAlignment;
41 
42   std::vector<llvm::Constant *> Elements;
43 
44   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
45     : CGM(CGM), CGF(CGF), Packed(false), NextFieldOffsetInBytes(0),
46     LLVMStructAlignment(1) { }
47 
48   bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
49                    const Expr *InitExpr) {
50     uint64_t FieldOffsetInBytes = FieldOffset / 8;
51 
52     assert(NextFieldOffsetInBytes <= FieldOffsetInBytes
53            && "Field offset mismatch!");
54 
55     // Emit the field.
56     llvm::Constant *C = CGM.EmitConstantExpr(InitExpr, Field->getType(), CGF);
57     if (!C)
58       return false;
59 
60     unsigned FieldAlignment = getAlignment(C);
61 
62     // Round up the field offset to the alignment of the field type.
63     uint64_t AlignedNextFieldOffsetInBytes =
64       llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
65 
66     if (AlignedNextFieldOffsetInBytes > FieldOffsetInBytes) {
67       assert(!Packed && "Alignment is wrong even with a packed struct!");
68 
69       // Convert the struct to a packed struct.
70       ConvertStructToPacked();
71 
72       AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes;
73     }
74 
75     if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
76       // We need to append padding.
77       AppendPadding(FieldOffsetInBytes - NextFieldOffsetInBytes);
78 
79       assert(NextFieldOffsetInBytes == FieldOffsetInBytes &&
80              "Did not add enough padding!");
81 
82       AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes;
83     }
84 
85     // Add the field.
86     Elements.push_back(C);
87     NextFieldOffsetInBytes = AlignedNextFieldOffsetInBytes + getSizeInBytes(C);
88     LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
89     return true;
90   }
91 
92   bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
93                       const Expr *InitExpr) {
94     llvm::ConstantInt *CI =
95       cast_or_null<llvm::ConstantInt>(CGM.EmitConstantExpr(InitExpr,
96                                                            Field->getType(),
97                                                            CGF));
98     // FIXME: Can this ever happen?
99     if (!CI)
100       return false;
101 
102     if (FieldOffset > NextFieldOffsetInBytes * 8) {
103       // We need to add padding.
104       uint64_t NumBytes =
105         llvm::RoundUpToAlignment(FieldOffset -
106                                  NextFieldOffsetInBytes * 8, 8) / 8;
107 
108       AppendPadding(NumBytes);
109     }
110 
111     uint64_t FieldSize =
112       Field->getBitWidth()->EvaluateAsInt(CGM.getContext()).getZExtValue();
113 
114     llvm::APInt FieldValue = CI->getValue();
115 
116     // Promote the size of FieldValue if necessary
117     // FIXME: This should never occur, but currently it can because initializer
118     // constants are cast to bool, and because clang is not enforcing bitfield
119     // width limits.
120     if (FieldSize > FieldValue.getBitWidth())
121       FieldValue.zext(FieldSize);
122 
123     // Truncate the size of FieldValue to the bit field size.
124     if (FieldSize < FieldValue.getBitWidth())
125       FieldValue.trunc(FieldSize);
126 
127     if (FieldOffset < NextFieldOffsetInBytes * 8) {
128       // Either part of the field or the entire field can go into the previous
129       // byte.
130       assert(!Elements.empty() && "Elements can't be empty!");
131 
132       unsigned BitsInPreviousByte =
133         NextFieldOffsetInBytes * 8 - FieldOffset;
134 
135       bool FitsCompletelyInPreviousByte =
136         BitsInPreviousByte >= FieldValue.getBitWidth();
137 
138       llvm::APInt Tmp = FieldValue;
139 
140       if (!FitsCompletelyInPreviousByte) {
141         unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
142 
143         if (CGM.getTargetData().isBigEndian()) {
144           Tmp = Tmp.lshr(NewFieldWidth);
145           Tmp.trunc(BitsInPreviousByte);
146 
147           // We want the remaining high bits.
148           FieldValue.trunc(NewFieldWidth);
149         } else {
150           Tmp.trunc(BitsInPreviousByte);
151 
152           // We want the remaining low bits.
153           FieldValue = FieldValue.lshr(BitsInPreviousByte);
154           FieldValue.trunc(NewFieldWidth);
155         }
156       }
157 
158       Tmp.zext(8);
159       if (CGM.getTargetData().isBigEndian()) {
160         if (FitsCompletelyInPreviousByte)
161           Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
162       } else {
163         Tmp = Tmp.shl(8 - BitsInPreviousByte);
164       }
165 
166       // Or in the bits that go into the previous byte.
167       Tmp |= cast<llvm::ConstantInt>(Elements.back())->getValue();
168       Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
169 
170       if (FitsCompletelyInPreviousByte)
171         return true;
172     }
173 
174     while (FieldValue.getBitWidth() > 8) {
175       llvm::APInt Tmp;
176 
177       if (CGM.getTargetData().isBigEndian()) {
178         // We want the high bits.
179         Tmp = FieldValue;
180         Tmp = Tmp.lshr(Tmp.getBitWidth() - 8);
181         Tmp.trunc(8);
182       } else {
183         // We want the low bits.
184         Tmp = FieldValue;
185         Tmp.trunc(8);
186 
187         FieldValue = FieldValue.lshr(8);
188       }
189 
190       Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
191       NextFieldOffsetInBytes++;
192 
193       FieldValue.trunc(FieldValue.getBitWidth() - 8);
194     }
195 
196     assert(FieldValue.getBitWidth() > 0 &&
197            "Should have at least one bit left!");
198     assert(FieldValue.getBitWidth() <= 8 &&
199            "Should not have more than a byte left!");
200 
201     if (FieldValue.getBitWidth() < 8) {
202       if (CGM.getTargetData().isBigEndian()) {
203         unsigned BitWidth = FieldValue.getBitWidth();
204 
205         FieldValue.zext(8);
206         FieldValue = FieldValue << (8 - BitWidth);
207       } else
208         FieldValue.zext(8);
209     }
210 
211     // Append the last element.
212     Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
213                                               FieldValue));
214     NextFieldOffsetInBytes++;
215     return true;
216   }
217 
218   void AppendPadding(uint64_t NumBytes) {
219     if (!NumBytes)
220       return;
221 
222     const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
223     if (NumBytes > 1)
224       Ty = llvm::ArrayType::get(Ty, NumBytes);
225 
226     llvm::Constant *C = llvm::Constant::getNullValue(Ty);
227     Elements.push_back(C);
228     assert(getAlignment(C) == 1 && "Padding must have 1 byte alignment!");
229 
230     NextFieldOffsetInBytes += getSizeInBytes(C);
231   }
232 
233   void AppendTailPadding(uint64_t RecordSize) {
234     assert(RecordSize % 8 == 0 && "Invalid record size!");
235 
236     uint64_t RecordSizeInBytes = RecordSize / 8;
237     assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
238 
239     unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
240     AppendPadding(NumPadBytes);
241   }
242 
243   void ConvertStructToPacked() {
244     std::vector<llvm::Constant *> PackedElements;
245     uint64_t ElementOffsetInBytes = 0;
246 
247     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
248       llvm::Constant *C = Elements[i];
249 
250       unsigned ElementAlign =
251         CGM.getTargetData().getABITypeAlignment(C->getType());
252       uint64_t AlignedElementOffsetInBytes =
253         llvm::RoundUpToAlignment(ElementOffsetInBytes, ElementAlign);
254 
255       if (AlignedElementOffsetInBytes > ElementOffsetInBytes) {
256         // We need some padding.
257         uint64_t NumBytes =
258           AlignedElementOffsetInBytes - ElementOffsetInBytes;
259 
260         const llvm::Type *Ty = llvm::Type::getInt8Ty(CGF->getLLVMContext());
261         if (NumBytes > 1)
262           Ty = llvm::ArrayType::get(Ty, NumBytes);
263 
264         llvm::Constant *Padding = llvm::Constant::getNullValue(Ty);
265         PackedElements.push_back(Padding);
266         ElementOffsetInBytes += getSizeInBytes(Padding);
267       }
268 
269       PackedElements.push_back(C);
270       ElementOffsetInBytes += getSizeInBytes(C);
271     }
272 
273     assert(ElementOffsetInBytes == NextFieldOffsetInBytes &&
274            "Packing the struct changed its size!");
275 
276     Elements = PackedElements;
277     LLVMStructAlignment = 1;
278     Packed = true;
279   }
280 
281   bool Build(InitListExpr *ILE) {
282     RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
283     const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
284 
285     unsigned FieldNo = 0;
286     unsigned ElementNo = 0;
287     for (RecordDecl::field_iterator Field = RD->field_begin(),
288          FieldEnd = RD->field_end();
289          ElementNo < ILE->getNumInits() && Field != FieldEnd;
290          ++Field, ++FieldNo) {
291       if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
292         continue;
293 
294       if (Field->isBitField()) {
295         if (!Field->getIdentifier())
296           continue;
297 
298         if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
299                             ILE->getInit(ElementNo)))
300           return false;
301       } else {
302         if (!AppendField(*Field, Layout.getFieldOffset(FieldNo),
303                          ILE->getInit(ElementNo)))
304           return false;
305       }
306 
307       ElementNo++;
308     }
309 
310     uint64_t LayoutSizeInBytes = Layout.getSize() / 8;
311 
312     if (NextFieldOffsetInBytes > LayoutSizeInBytes) {
313       // If the struct is bigger than the size of the record type,
314       // we must have a flexible array member at the end.
315       assert(RD->hasFlexibleArrayMember() &&
316              "Must have flexible array member if struct is bigger than type!");
317 
318       // No tail padding is necessary.
319       return true;
320     }
321 
322     uint64_t LLVMSizeInBytes = llvm::RoundUpToAlignment(NextFieldOffsetInBytes,
323                                                         LLVMStructAlignment);
324 
325     // Check if we need to convert the struct to a packed struct.
326     if (NextFieldOffsetInBytes <= LayoutSizeInBytes &&
327         LLVMSizeInBytes > LayoutSizeInBytes) {
328       assert(!Packed && "Size mismatch!");
329 
330       ConvertStructToPacked();
331       assert(NextFieldOffsetInBytes == LayoutSizeInBytes &&
332              "Converting to packed did not help!");
333     }
334 
335     // Append tail padding if necessary.
336     AppendTailPadding(Layout.getSize());
337 
338     assert(Layout.getSize() / 8 == NextFieldOffsetInBytes &&
339            "Tail padding mismatch!");
340 
341     return true;
342   }
343 
344   unsigned getAlignment(const llvm::Constant *C) const {
345     if (Packed)
346       return 1;
347 
348     return CGM.getTargetData().getABITypeAlignment(C->getType());
349   }
350 
351   uint64_t getSizeInBytes(const llvm::Constant *C) const {
352     return CGM.getTargetData().getTypeAllocSize(C->getType());
353   }
354 
355 public:
356   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
357                                      InitListExpr *ILE) {
358     ConstStructBuilder Builder(CGM, CGF);
359 
360     if (!Builder.Build(ILE))
361       return 0;
362 
363     llvm::Constant *Result =
364       llvm::ConstantStruct::get(CGM.getLLVMContext(),
365                                 Builder.Elements, Builder.Packed);
366 
367     assert(llvm::RoundUpToAlignment(Builder.NextFieldOffsetInBytes,
368                                     Builder.getAlignment(Result)) ==
369            Builder.getSizeInBytes(Result) && "Size mismatch!");
370 
371     return Result;
372   }
373 };
374 
375 class VISIBILITY_HIDDEN ConstExprEmitter :
376   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
377   CodeGenModule &CGM;
378   CodeGenFunction *CGF;
379   llvm::LLVMContext &VMContext;
380 public:
381   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
382     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
383   }
384 
385   //===--------------------------------------------------------------------===//
386   //                            Visitor Methods
387   //===--------------------------------------------------------------------===//
388 
389   llvm::Constant *VisitStmt(Stmt *S) {
390     return 0;
391   }
392 
393   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
394     return Visit(PE->getSubExpr());
395   }
396 
397   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
398     return Visit(E->getInitializer());
399   }
400 
401   llvm::Constant *VisitCastExpr(CastExpr* E) {
402     switch (E->getCastKind()) {
403     case CastExpr::CK_ToUnion: {
404       // GCC cast to union extension
405       assert(E->getType()->isUnionType() &&
406              "Destination type is not union type!");
407       const llvm::Type *Ty = ConvertType(E->getType());
408       Expr *SubExpr = E->getSubExpr();
409 
410       llvm::Constant *C =
411         CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF);
412       if (!C)
413         return 0;
414 
415       // Build a struct with the union sub-element as the first member,
416       // and padded to the appropriate size
417       std::vector<llvm::Constant*> Elts;
418       std::vector<const llvm::Type*> Types;
419       Elts.push_back(C);
420       Types.push_back(C->getType());
421       unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
422       unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty);
423 
424       assert(CurSize <= TotalSize && "Union size mismatch!");
425       if (unsigned NumPadBytes = TotalSize - CurSize) {
426         const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
427         if (NumPadBytes > 1)
428           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
429 
430         Elts.push_back(llvm::Constant::getNullValue(Ty));
431         Types.push_back(Ty);
432       }
433 
434       llvm::StructType* STy =
435         llvm::StructType::get(C->getType()->getContext(), Types, false);
436       return llvm::ConstantStruct::get(STy, Elts);
437     }
438     case CastExpr::CK_NullToMemberPointer:
439       return CGM.EmitNullConstant(E->getType());
440     default: {
441       // FIXME: This should be handled by the CK_NoOp cast kind.
442       // Explicit and implicit no-op casts
443       QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType();
444       if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy))
445           return Visit(E->getSubExpr());
446       return 0;
447     }
448     }
449   }
450 
451   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
452     return Visit(DAE->getExpr());
453   }
454 
455   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
456     std::vector<llvm::Constant*> Elts;
457     const llvm::ArrayType *AType =
458         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
459     unsigned NumInitElements = ILE->getNumInits();
460     // FIXME: Check for wide strings
461     // FIXME: Check for NumInitElements exactly equal to 1??
462     if (NumInitElements > 0 &&
463         (isa<StringLiteral>(ILE->getInit(0)) ||
464          isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
465         ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
466       return Visit(ILE->getInit(0));
467     const llvm::Type *ElemTy = AType->getElementType();
468     unsigned NumElements = AType->getNumElements();
469 
470     // Initialising an array requires us to automatically
471     // initialise any elements that have not been initialised explicitly
472     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
473 
474     // Copy initializer elements.
475     unsigned i = 0;
476     bool RewriteType = false;
477     for (; i < NumInitableElts; ++i) {
478       Expr *Init = ILE->getInit(i);
479       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
480       if (!C)
481         return 0;
482       RewriteType |= (C->getType() != ElemTy);
483       Elts.push_back(C);
484     }
485 
486     // Initialize remaining array elements.
487     // FIXME: This doesn't handle member pointers correctly!
488     for (; i < NumElements; ++i)
489       Elts.push_back(llvm::Constant::getNullValue(ElemTy));
490 
491     if (RewriteType) {
492       // FIXME: Try to avoid packing the array
493       std::vector<const llvm::Type*> Types;
494       for (unsigned i = 0; i < Elts.size(); ++i)
495         Types.push_back(Elts[i]->getType());
496       const llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
497                                                             Types, true);
498       return llvm::ConstantStruct::get(SType, Elts);
499     }
500 
501     return llvm::ConstantArray::get(AType, Elts);
502   }
503 
504   llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
505     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
506   }
507 
508   llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
509     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
510   }
511 
512   llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
513     const llvm::VectorType *VType =
514         cast<llvm::VectorType>(ConvertType(ILE->getType()));
515     const llvm::Type *ElemTy = VType->getElementType();
516     std::vector<llvm::Constant*> Elts;
517     unsigned NumElements = VType->getNumElements();
518     unsigned NumInitElements = ILE->getNumInits();
519 
520     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
521 
522     // Copy initializer elements.
523     unsigned i = 0;
524     for (; i < NumInitableElts; ++i) {
525       Expr *Init = ILE->getInit(i);
526       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
527       if (!C)
528         return 0;
529       Elts.push_back(C);
530     }
531 
532     for (; i < NumElements; ++i)
533       Elts.push_back(llvm::Constant::getNullValue(ElemTy));
534 
535     return llvm::ConstantVector::get(VType, Elts);
536   }
537 
538   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
539     return CGM.EmitNullConstant(E->getType());
540   }
541 
542   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
543     if (ILE->getType()->isScalarType()) {
544       // We have a scalar in braces. Just use the first element.
545       if (ILE->getNumInits() > 0) {
546         Expr *Init = ILE->getInit(0);
547         return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
548       }
549       return CGM.EmitNullConstant(ILE->getType());
550     }
551 
552     if (ILE->getType()->isArrayType())
553       return EmitArrayInitialization(ILE);
554 
555     if (ILE->getType()->isStructureType())
556       return EmitStructInitialization(ILE);
557 
558     if (ILE->getType()->isUnionType())
559       return EmitUnionInitialization(ILE);
560 
561     if (ILE->getType()->isVectorType())
562       return EmitVectorInitialization(ILE);
563 
564     assert(0 && "Unable to handle InitListExpr");
565     // Get rid of control reaches end of void function warning.
566     // Not reached.
567     return 0;
568   }
569 
570   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
571     assert(!E->getType()->isPointerType() && "Strings are always arrays");
572 
573     // This must be a string initializing an array in a static initializer.
574     // Don't emit it as the address of the string, emit the string data itself
575     // as an inline array.
576     return llvm::ConstantArray::get(VMContext,
577                                     CGM.GetStringForStringLiteral(E), false);
578   }
579 
580   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
581     // This must be an @encode initializing an array in a static initializer.
582     // Don't emit it as the address of the string, emit the string data itself
583     // as an inline array.
584     std::string Str;
585     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
586     const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
587 
588     // Resize the string to the right size, adding zeros at the end, or
589     // truncating as needed.
590     Str.resize(CAT->getSize().getZExtValue(), '\0');
591     return llvm::ConstantArray::get(VMContext, Str, false);
592   }
593 
594   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
595     return Visit(E->getSubExpr());
596   }
597 
598   // Utility methods
599   const llvm::Type *ConvertType(QualType T) {
600     return CGM.getTypes().ConvertType(T);
601   }
602 
603 public:
604   llvm::Constant *EmitLValue(Expr *E) {
605     switch (E->getStmtClass()) {
606     default: break;
607     case Expr::CompoundLiteralExprClass: {
608       // Note that due to the nature of compound literals, this is guaranteed
609       // to be the only use of the variable, so we just generate it here.
610       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
611       llvm::Constant* C = Visit(CLE->getInitializer());
612       // FIXME: "Leaked" on failure.
613       if (C)
614         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
615                                      E->getType().isConstant(CGM.getContext()),
616                                      llvm::GlobalValue::InternalLinkage,
617                                      C, ".compoundliteral", 0, false,
618                                      E->getType().getAddressSpace());
619       return C;
620     }
621     case Expr::DeclRefExprClass:
622     case Expr::QualifiedDeclRefExprClass: {
623       NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
624       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
625         return CGM.GetAddrOfFunction(FD);
626       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
627         // We can never refer to a variable with local storage.
628         if (!VD->hasLocalStorage()) {
629           if (VD->isFileVarDecl() || VD->hasExternalStorage())
630             return CGM.GetAddrOfGlobalVar(VD);
631           else if (VD->isBlockVarDecl()) {
632             assert(CGF && "Can't access static local vars without CGF");
633             return CGF->GetAddrOfStaticLocalVar(VD);
634           }
635         }
636       }
637       break;
638     }
639     case Expr::StringLiteralClass:
640       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
641     case Expr::ObjCEncodeExprClass:
642       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
643     case Expr::ObjCStringLiteralClass: {
644       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
645       llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL);
646       return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
647     }
648     case Expr::PredefinedExprClass: {
649       // __func__/__FUNCTION__ -> "".  __PRETTY_FUNCTION__ -> "top level".
650       std::string Str;
651       if (cast<PredefinedExpr>(E)->getIdentType() ==
652           PredefinedExpr::PrettyFunction)
653         Str = "top level";
654 
655       return CGM.GetAddrOfConstantCString(Str, ".tmp");
656     }
657     case Expr::AddrLabelExprClass: {
658       assert(CGF && "Invalid address of label expression outside function.");
659       unsigned id =
660           CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
661       llvm::Constant *C =
662             llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), id);
663       return llvm::ConstantExpr::getIntToPtr(C, ConvertType(E->getType()));
664     }
665     case Expr::CallExprClass: {
666       CallExpr* CE = cast<CallExpr>(E);
667       if (CE->isBuiltinCall(CGM.getContext()) !=
668             Builtin::BI__builtin___CFStringMakeConstantString)
669         break;
670       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
671       const StringLiteral *Literal = cast<StringLiteral>(Arg);
672       // FIXME: need to deal with UCN conversion issues.
673       return CGM.GetAddrOfConstantCFString(Literal);
674     }
675     case Expr::BlockExprClass: {
676       std::string FunctionName;
677       if (CGF)
678         FunctionName = CGF->CurFn->getName();
679       else
680         FunctionName = "global";
681 
682       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
683     }
684     }
685 
686     return 0;
687   }
688 };
689 
690 }  // end anonymous namespace.
691 
692 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
693                                                 QualType DestType,
694                                                 CodeGenFunction *CGF) {
695   Expr::EvalResult Result;
696 
697   bool Success = false;
698 
699   if (DestType->isReferenceType())
700     Success = E->EvaluateAsLValue(Result, Context);
701   else
702     Success = E->Evaluate(Result, Context);
703 
704   if (Success) {
705     assert(!Result.HasSideEffects &&
706            "Constant expr should not have any side effects!");
707     switch (Result.Val.getKind()) {
708     case APValue::Uninitialized:
709       assert(0 && "Constant expressions should be initialized.");
710       return 0;
711     case APValue::LValue: {
712       const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
713       llvm::Constant *Offset =
714         llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
715                                Result.Val.getLValueOffset());
716 
717       llvm::Constant *C;
718       if (const Expr *LVBase = Result.Val.getLValueBase()) {
719         C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
720 
721         // Apply offset if necessary.
722         if (!Offset->isNullValue()) {
723           const llvm::Type *Type =
724             llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
725           llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
726           Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1);
727           C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
728         }
729 
730         // Convert to the appropriate type; this could be an lvalue for
731         // an integer.
732         if (isa<llvm::PointerType>(DestTy))
733           return llvm::ConstantExpr::getBitCast(C, DestTy);
734 
735         return llvm::ConstantExpr::getPtrToInt(C, DestTy);
736       } else {
737         C = Offset;
738 
739         // Convert to the appropriate type; this could be an lvalue for
740         // an integer.
741         if (isa<llvm::PointerType>(DestTy))
742           return llvm::ConstantExpr::getIntToPtr(C, DestTy);
743 
744         // If the types don't match this should only be a truncate.
745         if (C->getType() != DestTy)
746           return llvm::ConstantExpr::getTrunc(C, DestTy);
747 
748         return C;
749       }
750     }
751     case APValue::Int: {
752       llvm::Constant *C = llvm::ConstantInt::get(VMContext,
753                                                  Result.Val.getInt());
754 
755       if (C->getType() == llvm::Type::getInt1Ty(VMContext)) {
756         const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
757         C = llvm::ConstantExpr::getZExt(C, BoolTy);
758       }
759       return C;
760     }
761     case APValue::ComplexInt: {
762       llvm::Constant *Complex[2];
763 
764       Complex[0] = llvm::ConstantInt::get(VMContext,
765                                           Result.Val.getComplexIntReal());
766       Complex[1] = llvm::ConstantInt::get(VMContext,
767                                           Result.Val.getComplexIntImag());
768 
769       // FIXME: the target may want to specify that this is packed.
770       return llvm::ConstantStruct::get(VMContext, Complex, 2, false);
771     }
772     case APValue::Float:
773       return llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
774     case APValue::ComplexFloat: {
775       llvm::Constant *Complex[2];
776 
777       Complex[0] = llvm::ConstantFP::get(VMContext,
778                                          Result.Val.getComplexFloatReal());
779       Complex[1] = llvm::ConstantFP::get(VMContext,
780                                          Result.Val.getComplexFloatImag());
781 
782       // FIXME: the target may want to specify that this is packed.
783       return llvm::ConstantStruct::get(VMContext, Complex, 2, false);
784     }
785     case APValue::Vector: {
786       llvm::SmallVector<llvm::Constant *, 4> Inits;
787       unsigned NumElts = Result.Val.getVectorLength();
788 
789       for (unsigned i = 0; i != NumElts; ++i) {
790         APValue &Elt = Result.Val.getVectorElt(i);
791         if (Elt.isInt())
792           Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
793         else
794           Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
795       }
796       return llvm::ConstantVector::get(&Inits[0], Inits.size());
797     }
798     }
799   }
800 
801   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
802   if (C && C->getType() == llvm::Type::getInt1Ty(VMContext)) {
803     const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
804     C = llvm::ConstantExpr::getZExt(C, BoolTy);
805   }
806   return C;
807 }
808 
809 static inline bool isDataMemberPointerType(QualType T) {
810   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
811     return !MPT->getPointeeType()->isFunctionType();
812 
813   return false;
814 }
815 
816 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
817   // No need to check for member pointers when not compiling C++.
818   if (!getContext().getLangOptions().CPlusPlus)
819     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
820 
821   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
822 
823     QualType ElementTy = CAT->getElementType();
824 
825     // FIXME: Handle arrays of structs that contain member pointers.
826     if (isDataMemberPointerType(Context.getBaseElementType(ElementTy))) {
827       llvm::Constant *Element = EmitNullConstant(ElementTy);
828       uint64_t NumElements = CAT->getSize().getZExtValue();
829       std::vector<llvm::Constant *> Array(NumElements);
830       for (uint64_t i = 0; i != NumElements; ++i)
831         Array[i] = Element;
832 
833       const llvm::ArrayType *ATy =
834         cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
835       return llvm::ConstantArray::get(ATy, Array);
836     }
837   }
838 
839   if (const RecordType *RT = T->getAs<RecordType>()) {
840     const RecordDecl *RD = RT->getDecl();
841     // FIXME: It would be better if there was a way to explicitly compute the
842     // record layout instead of converting to a type.
843     Types.ConvertTagDeclType(RD);
844 
845     const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
846     if (Layout.containsMemberPointer()) {
847       assert(0 && "FIXME: No support for structs with member pointers yet!");
848     }
849   }
850 
851   // FIXME: Handle structs that contain member pointers.
852   if (isDataMemberPointerType(T))
853     return llvm::Constant::getAllOnesValue(getTypes().ConvertTypeForMem(T));
854 
855   return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
856 }
857