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   std::vector<llvm::Constant *> Elements;
41 
42   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
43     : CGM(CGM), CGF(CGF), Packed(false), NextFieldOffsetInBytes(0) { }
44 
45   bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
46                    const Expr *InitExpr) {
47     uint64_t FieldOffsetInBytes = FieldOffset / 8;
48 
49     assert(NextFieldOffsetInBytes <= FieldOffsetInBytes
50            && "Field offset mismatch!");
51 
52     // Emit the field.
53     llvm::Constant *C = CGM.EmitConstantExpr(InitExpr, Field->getType(), CGF);
54     if (!C)
55       return false;
56 
57     unsigned FieldAlignment = getAlignment(C);
58 
59     // Round up the field offset to the alignment of the field type.
60     uint64_t AlignedNextFieldOffsetInBytes =
61       llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
62 
63     if (AlignedNextFieldOffsetInBytes > FieldOffsetInBytes) {
64       // FIXME: Must convert the struct to a packed struct.
65       return false;
66     }
67 
68     if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
69       // We need to append padding.
70       AppendPadding(FieldOffsetInBytes - AlignedNextFieldOffsetInBytes);
71 
72       assert(NextFieldOffsetInBytes == FieldOffsetInBytes &&
73              "Did not add enough padding!");
74 
75       AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes;
76     }
77 
78     // Add the field.
79     Elements.push_back(C);
80     NextFieldOffsetInBytes = AlignedNextFieldOffsetInBytes + getSizeInBytes(C);
81 
82     return true;
83   }
84 
85   void AppendPadding(uint64_t NumBytes) {
86     if (!NumBytes)
87       return;
88 
89     const llvm::Type *Ty = llvm::Type::Int8Ty;
90     if (NumBytes > 1)
91       Ty = CGM.getLLVMContext().getArrayType(Ty, NumBytes);
92 
93     llvm::Constant *C = CGM.getLLVMContext().getNullValue(Ty);
94     Elements.push_back(C);
95     assert(getAlignment(C) == 1 && "Padding must have 1 byte alignment!");
96 
97     NextFieldOffsetInBytes += getSizeInBytes(C);
98   }
99 
100   void AppendTailPadding(uint64_t RecordSize) {
101     assert(RecordSize % 8 == 0 && "Invalid record size!");
102 
103     uint64_t RecordSizeInBytes = RecordSize / 8;
104     assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
105 
106     unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
107     AppendPadding(NumPadBytes);
108   }
109 
110   bool Build(const InitListExpr *ILE) {
111     RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
112     const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
113 
114     unsigned FieldNo = 0;
115     unsigned ElementNo = 0;
116     for (RecordDecl::field_iterator Field = RD->field_begin(),
117          FieldEnd = RD->field_end();
118          ElementNo < ILE->getNumInits() && Field != FieldEnd;
119          ++Field, ++FieldNo) {
120       if (Field->isBitField()) {
121         if (!Field->getIdentifier())
122           continue;
123 
124         // FIXME: Bitfield support.
125         return false;
126       } else {
127         if (!AppendField(*Field, Layout.getFieldOffset(FieldNo),
128                          ILE->getInit(ElementNo)))
129           return false;
130       }
131 
132       ElementNo++;
133     }
134 
135     uint64_t LayoutSizeInBytes = Layout.getSize() / 8;
136 
137     if (NextFieldOffsetInBytes > LayoutSizeInBytes) {
138       // If the struct is bigger than the size of the record type,
139       // we must have a flexible array member at the end.
140       assert(RD->hasFlexibleArrayMember() &&
141              "Must have flexible array member if struct is bigger than type!");
142 
143       // No tail padding is necessary.
144       return true;
145     }
146 
147     // Append tail padding if necessary.
148     AppendTailPadding(Layout.getSize());
149 
150     assert(Layout.getSize() / 8 == NextFieldOffsetInBytes &&
151            "Tail padding mismatch!");
152 
153     return true;
154   }
155 
156   unsigned getAlignment(const llvm::Constant *C) const {
157     if (Packed)
158       return 1;
159 
160     return CGM.getTargetData().getABITypeAlignment(C->getType());
161   }
162 
163   uint64_t getSizeInBytes(const llvm::Constant *C) const {
164     return CGM.getTargetData().getTypeAllocSize(C->getType());
165   }
166 
167 public:
168   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
169                                      const InitListExpr *ILE) {
170     ConstStructBuilder Builder(CGM, CGF);
171 
172     if (!Builder.Build(ILE))
173       return 0;
174 
175     llvm::Constant *Result =
176       CGM.getLLVMContext().getConstantStruct(Builder.Elements, Builder.Packed);
177 
178     assert(llvm::RoundUpToAlignment(Builder.NextFieldOffsetInBytes,
179                                     Builder.getAlignment(Result)) ==
180            Builder.getSizeInBytes(Result) && "Size mismatch!");
181 
182     return Result;
183   }
184 };
185 
186 class VISIBILITY_HIDDEN ConstExprEmitter :
187   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
188   CodeGenModule &CGM;
189   CodeGenFunction *CGF;
190   llvm::LLVMContext &VMContext;
191 public:
192   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
193     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
194   }
195 
196   //===--------------------------------------------------------------------===//
197   //                            Visitor Methods
198   //===--------------------------------------------------------------------===//
199 
200   llvm::Constant *VisitStmt(Stmt *S) {
201     return 0;
202   }
203 
204   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
205     return Visit(PE->getSubExpr());
206   }
207 
208   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
209     return Visit(E->getInitializer());
210   }
211 
212   llvm::Constant *VisitCastExpr(CastExpr* E) {
213     // GCC cast to union extension
214     if (E->getType()->isUnionType()) {
215       const llvm::Type *Ty = ConvertType(E->getType());
216       Expr *SubExpr = E->getSubExpr();
217       return EmitUnion(CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF),
218                        Ty);
219     }
220     // Explicit and implicit no-op casts
221     QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType();
222     if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy)) {
223       return Visit(E->getSubExpr());
224     }
225     return 0;
226   }
227 
228   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
229     return Visit(DAE->getExpr());
230   }
231 
232   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
233     std::vector<llvm::Constant*> Elts;
234     const llvm::ArrayType *AType =
235         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
236     unsigned NumInitElements = ILE->getNumInits();
237     // FIXME: Check for wide strings
238     // FIXME: Check for NumInitElements exactly equal to 1??
239     if (NumInitElements > 0 &&
240         (isa<StringLiteral>(ILE->getInit(0)) ||
241          isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
242         ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
243       return Visit(ILE->getInit(0));
244     const llvm::Type *ElemTy = AType->getElementType();
245     unsigned NumElements = AType->getNumElements();
246 
247     // Initialising an array requires us to automatically
248     // initialise any elements that have not been initialised explicitly
249     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
250 
251     // Copy initializer elements.
252     unsigned i = 0;
253     bool RewriteType = false;
254     for (; i < NumInitableElts; ++i) {
255       Expr *Init = ILE->getInit(i);
256       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
257       if (!C)
258         return 0;
259       RewriteType |= (C->getType() != ElemTy);
260       Elts.push_back(C);
261     }
262 
263     // Initialize remaining array elements.
264     // FIXME: This doesn't handle member pointers correctly!
265     for (; i < NumElements; ++i)
266       Elts.push_back(VMContext.getNullValue(ElemTy));
267 
268     if (RewriteType) {
269       // FIXME: Try to avoid packing the array
270       std::vector<const llvm::Type*> Types;
271       for (unsigned i = 0; i < Elts.size(); ++i)
272         Types.push_back(Elts[i]->getType());
273       const llvm::StructType *SType = VMContext.getStructType(Types, true);
274       return VMContext.getConstantStruct(SType, Elts);
275     }
276 
277     return VMContext.getConstantArray(AType, Elts);
278   }
279 
280   void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts,
281                                 FieldDecl* Field, Expr* E) {
282     // Calculate the value to insert
283     llvm::Constant *C = CGM.EmitConstantExpr(E, Field->getType(), CGF);
284     if (!C)
285       return;
286 
287     llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
288     if (!CI) {
289       CGM.ErrorUnsupported(E, "bitfield initialization");
290       return;
291     }
292     llvm::APInt V = CI->getValue();
293 
294     // Calculate information about the relevant field
295     const llvm::Type* Ty = CI->getType();
296     const llvm::TargetData &TD = CGM.getTypes().getTargetData();
297     unsigned size = TD.getTypeAllocSizeInBits(Ty);
298     CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field);
299     unsigned FieldOffset = Info.FieldNo * size;
300 
301     FieldOffset += Info.Start;
302 
303     // Find where to start the insertion
304     // FIXME: This is O(n^2) in the number of bit-fields!
305     // FIXME: This won't work if the struct isn't completely packed!
306     unsigned offset = 0, i = 0;
307     while (offset < (FieldOffset & -8))
308       offset += TD.getTypeAllocSizeInBits(Elts[i++]->getType());
309 
310     // Advance over 0 sized elements (must terminate in bounds since
311     // the bitfield must have a size).
312     while (TD.getTypeAllocSizeInBits(Elts[i]->getType()) == 0)
313       ++i;
314 
315     // Promote the size of V if necessary
316     // FIXME: This should never occur, but currently it can because initializer
317     // constants are cast to bool, and because clang is not enforcing bitfield
318     // width limits.
319     if (Info.Size > V.getBitWidth())
320       V.zext(Info.Size);
321 
322     // Insert the bits into the struct
323     // FIXME: This algorthm is only correct on X86!
324     // FIXME: THis algorthm assumes bit-fields only have byte-size elements!
325     unsigned bitsToInsert = Info.Size;
326     unsigned curBits = std::min(8 - (FieldOffset & 7), bitsToInsert);
327     unsigned byte = V.getLoBits(curBits).getZExtValue() << (FieldOffset & 7);
328     do {
329       llvm::Constant* byteC =
330         llvm::ConstantInt::get(llvm::Type::Int8Ty, byte);
331       Elts[i] = VMContext.getConstantExprOr(Elts[i], byteC);
332       ++i;
333       V = V.lshr(curBits);
334       bitsToInsert -= curBits;
335 
336       if (!bitsToInsert)
337         break;
338 
339       curBits = bitsToInsert > 8 ? 8 : bitsToInsert;
340       byte = V.getLoBits(curBits).getZExtValue();
341     } while (true);
342   }
343 
344   llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
345     // FIXME: Use the returned struct when the builder works well enough.
346     ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
347 
348     const llvm::StructType *SType =
349         cast<llvm::StructType>(ConvertType(ILE->getType()));
350     RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
351     std::vector<llvm::Constant*> Elts;
352 
353     // Initialize the whole structure to zero.
354     // FIXME: This doesn't handle member pointers correctly!
355     for (unsigned i = 0; i < SType->getNumElements(); ++i) {
356       const llvm::Type *FieldTy = SType->getElementType(i);
357       Elts.push_back(VMContext.getNullValue(FieldTy));
358     }
359 
360     // Copy initializer elements. Skip padding fields.
361     unsigned EltNo = 0;  // Element no in ILE
362     bool RewriteType = false;
363     for (RecordDecl::field_iterator Field = RD->field_begin(),
364                                  FieldEnd = RD->field_end();
365          EltNo < ILE->getNumInits() && Field != FieldEnd; ++Field) {
366       if (Field->isBitField()) {
367         if (!Field->getIdentifier())
368           continue;
369         InsertBitfieldIntoStruct(Elts, *Field, ILE->getInit(EltNo));
370       } else {
371         unsigned FieldNo = CGM.getTypes().getLLVMFieldNo(*Field);
372         llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(EltNo),
373                                                  Field->getType(), CGF);
374         if (!C) return 0;
375         RewriteType |= (C->getType() != Elts[FieldNo]->getType());
376         Elts[FieldNo] = C;
377       }
378       EltNo++;
379     }
380 
381     if (RewriteType) {
382       // FIXME: Make this work for non-packed structs
383       assert(SType->isPacked() && "Cannot recreate unpacked structs");
384       std::vector<const llvm::Type*> Types;
385       for (unsigned i = 0; i < Elts.size(); ++i)
386         Types.push_back(Elts[i]->getType());
387       SType = VMContext.getStructType(Types, true);
388     }
389 
390     return VMContext.getConstantStruct(SType, Elts);
391   }
392 
393   llvm::Constant *EmitUnion(llvm::Constant *C, const llvm::Type *Ty) {
394     if (!C)
395       return 0;
396 
397     // Build a struct with the union sub-element as the first member,
398     // and padded to the appropriate size
399     std::vector<llvm::Constant*> Elts;
400     std::vector<const llvm::Type*> Types;
401     Elts.push_back(C);
402     Types.push_back(C->getType());
403     unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
404     unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty);
405 
406     assert(CurSize <= TotalSize && "Union size mismatch!");
407     if (unsigned NumPadBytes = TotalSize - CurSize) {
408       const llvm::Type *Ty = llvm::Type::Int8Ty;
409       if (NumPadBytes > 1)
410         Ty = VMContext.getArrayType(Ty, NumPadBytes);
411 
412       Elts.push_back(VMContext.getNullValue(Ty));
413       Types.push_back(Ty);
414     }
415 
416     llvm::StructType* STy = VMContext.getStructType(Types, false);
417     return VMContext.getConstantStruct(STy, Elts);
418   }
419 
420   llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
421     const llvm::Type *Ty = ConvertType(ILE->getType());
422 
423     FieldDecl* curField = ILE->getInitializedFieldInUnion();
424     if (!curField) {
425       // There's no field to initialize, so value-initialize the union.
426 #ifndef NDEBUG
427       // Make sure that it's really an empty and not a failure of
428       // semantic analysis.
429       RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
430       for (RecordDecl::field_iterator Field = RD->field_begin(),
431                                    FieldEnd = RD->field_end();
432            Field != FieldEnd; ++Field)
433         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
434 #endif
435       return VMContext.getNullValue(Ty);
436     }
437 
438     if (curField->isBitField()) {
439       // Create a dummy struct for bit-field insertion
440       unsigned NumElts = CGM.getTargetData().getTypeAllocSize(Ty);
441       llvm::Constant* NV =
442         VMContext.getNullValue(llvm::Type::Int8Ty);
443       std::vector<llvm::Constant*> Elts(NumElts, NV);
444 
445       InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0));
446       const llvm::ArrayType *RetTy =
447           VMContext.getArrayType(NV->getType(), NumElts);
448       return VMContext.getConstantArray(RetTy, Elts);
449     }
450 
451     llvm::Constant *InitElem;
452     if (ILE->getNumInits() > 0) {
453       Expr *Init = ILE->getInit(0);
454       InitElem = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
455     } else {
456       InitElem = CGM.EmitNullConstant(curField->getType());
457     }
458     return EmitUnion(InitElem, Ty);
459   }
460 
461   llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
462     const llvm::VectorType *VType =
463         cast<llvm::VectorType>(ConvertType(ILE->getType()));
464     const llvm::Type *ElemTy = VType->getElementType();
465     std::vector<llvm::Constant*> Elts;
466     unsigned NumElements = VType->getNumElements();
467     unsigned NumInitElements = ILE->getNumInits();
468 
469     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
470 
471     // Copy initializer elements.
472     unsigned i = 0;
473     for (; i < NumInitableElts; ++i) {
474       Expr *Init = ILE->getInit(i);
475       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
476       if (!C)
477         return 0;
478       Elts.push_back(C);
479     }
480 
481     for (; i < NumElements; ++i)
482       Elts.push_back(VMContext.getNullValue(ElemTy));
483 
484     return VMContext.getConstantVector(VType, Elts);
485   }
486 
487   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
488     return CGM.EmitNullConstant(E->getType());
489   }
490 
491   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
492     if (ILE->getType()->isScalarType()) {
493       // We have a scalar in braces. Just use the first element.
494       if (ILE->getNumInits() > 0) {
495         Expr *Init = ILE->getInit(0);
496         return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
497       }
498       return CGM.EmitNullConstant(ILE->getType());
499     }
500 
501     if (ILE->getType()->isArrayType())
502       return EmitArrayInitialization(ILE);
503 
504     if (ILE->getType()->isStructureType())
505       return EmitStructInitialization(ILE);
506 
507     if (ILE->getType()->isUnionType())
508       return EmitUnionInitialization(ILE);
509 
510     if (ILE->getType()->isVectorType())
511       return EmitVectorInitialization(ILE);
512 
513     assert(0 && "Unable to handle InitListExpr");
514     // Get rid of control reaches end of void function warning.
515     // Not reached.
516     return 0;
517   }
518 
519   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
520     assert(!E->getType()->isPointerType() && "Strings are always arrays");
521 
522     // This must be a string initializing an array in a static initializer.
523     // Don't emit it as the address of the string, emit the string data itself
524     // as an inline array.
525     return VMContext.getConstantArray(CGM.GetStringForStringLiteral(E), false);
526   }
527 
528   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
529     // This must be an @encode initializing an array in a static initializer.
530     // Don't emit it as the address of the string, emit the string data itself
531     // as an inline array.
532     std::string Str;
533     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
534     const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
535 
536     // Resize the string to the right size, adding zeros at the end, or
537     // truncating as needed.
538     Str.resize(CAT->getSize().getZExtValue(), '\0');
539     return VMContext.getConstantArray(Str, false);
540   }
541 
542   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
543     return Visit(E->getSubExpr());
544   }
545 
546   // Utility methods
547   const llvm::Type *ConvertType(QualType T) {
548     return CGM.getTypes().ConvertType(T);
549   }
550 
551 public:
552   llvm::Constant *EmitLValue(Expr *E) {
553     switch (E->getStmtClass()) {
554     default: break;
555     case Expr::CompoundLiteralExprClass: {
556       // Note that due to the nature of compound literals, this is guaranteed
557       // to be the only use of the variable, so we just generate it here.
558       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
559       llvm::Constant* C = Visit(CLE->getInitializer());
560       // FIXME: "Leaked" on failure.
561       if (C)
562         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
563                                      E->getType().isConstQualified(),
564                                      llvm::GlobalValue::InternalLinkage,
565                                      C, ".compoundliteral");
566       return C;
567     }
568     case Expr::DeclRefExprClass:
569     case Expr::QualifiedDeclRefExprClass: {
570       NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
571       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
572         return CGM.GetAddrOfFunction(GlobalDecl(FD));
573       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
574         // We can never refer to a variable with local storage.
575         if (!VD->hasLocalStorage()) {
576           if (VD->isFileVarDecl() || VD->hasExternalStorage())
577             return CGM.GetAddrOfGlobalVar(VD);
578           else if (VD->isBlockVarDecl()) {
579             assert(CGF && "Can't access static local vars without CGF");
580             return CGF->GetAddrOfStaticLocalVar(VD);
581           }
582         }
583       }
584       break;
585     }
586     case Expr::StringLiteralClass:
587       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
588     case Expr::ObjCEncodeExprClass:
589       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
590     case Expr::ObjCStringLiteralClass: {
591       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
592       llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL);
593       return VMContext.getConstantExprBitCast(C, ConvertType(E->getType()));
594     }
595     case Expr::PredefinedExprClass: {
596       // __func__/__FUNCTION__ -> "".  __PRETTY_FUNCTION__ -> "top level".
597       std::string Str;
598       if (cast<PredefinedExpr>(E)->getIdentType() ==
599           PredefinedExpr::PrettyFunction)
600         Str = "top level";
601 
602       return CGM.GetAddrOfConstantCString(Str, ".tmp");
603     }
604     case Expr::AddrLabelExprClass: {
605       assert(CGF && "Invalid address of label expression outside function.");
606       unsigned id = CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
607       llvm::Constant *C = llvm::ConstantInt::get(llvm::Type::Int32Ty, id);
608       return VMContext.getConstantExprIntToPtr(C, ConvertType(E->getType()));
609     }
610     case Expr::CallExprClass: {
611       CallExpr* CE = cast<CallExpr>(E);
612       if (CE->isBuiltinCall(CGM.getContext()) !=
613             Builtin::BI__builtin___CFStringMakeConstantString)
614         break;
615       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
616       const StringLiteral *Literal = cast<StringLiteral>(Arg);
617       // FIXME: need to deal with UCN conversion issues.
618       return CGM.GetAddrOfConstantCFString(Literal);
619     }
620     case Expr::BlockExprClass: {
621       std::string FunctionName;
622       if (CGF)
623         FunctionName = CGF->CurFn->getName();
624       else
625         FunctionName = "global";
626 
627       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
628     }
629     }
630 
631     return 0;
632   }
633 };
634 
635 }  // end anonymous namespace.
636 
637 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
638                                                 QualType DestType,
639                                                 CodeGenFunction *CGF) {
640   Expr::EvalResult Result;
641 
642   bool Success = false;
643 
644   if (DestType->isReferenceType())
645     Success = E->EvaluateAsLValue(Result, Context);
646   else
647     Success = E->Evaluate(Result, Context);
648 
649   if (Success) {
650     assert(!Result.HasSideEffects &&
651            "Constant expr should not have any side effects!");
652     switch (Result.Val.getKind()) {
653     case APValue::Uninitialized:
654       assert(0 && "Constant expressions should be initialized.");
655       return 0;
656     case APValue::LValue: {
657       const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
658       llvm::Constant *Offset =
659         llvm::ConstantInt::get(llvm::Type::Int64Ty,
660                                Result.Val.getLValueOffset());
661 
662       llvm::Constant *C;
663       if (const Expr *LVBase = Result.Val.getLValueBase()) {
664         C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
665 
666         // Apply offset if necessary.
667         if (!Offset->isNullValue()) {
668           const llvm::Type *Type =
669             VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
670           llvm::Constant *Casted = VMContext.getConstantExprBitCast(C, Type);
671           Casted = VMContext.getConstantExprGetElementPtr(Casted, &Offset, 1);
672           C = VMContext.getConstantExprBitCast(Casted, C->getType());
673         }
674 
675         // Convert to the appropriate type; this could be an lvalue for
676         // an integer.
677         if (isa<llvm::PointerType>(DestTy))
678           return VMContext.getConstantExprBitCast(C, DestTy);
679 
680         return VMContext.getConstantExprPtrToInt(C, DestTy);
681       } else {
682         C = Offset;
683 
684         // Convert to the appropriate type; this could be an lvalue for
685         // an integer.
686         if (isa<llvm::PointerType>(DestTy))
687           return VMContext.getConstantExprIntToPtr(C, DestTy);
688 
689         // If the types don't match this should only be a truncate.
690         if (C->getType() != DestTy)
691           return VMContext.getConstantExprTrunc(C, DestTy);
692 
693         return C;
694       }
695     }
696     case APValue::Int: {
697       llvm::Constant *C = llvm::ConstantInt::get(VMContext,
698                                                  Result.Val.getInt());
699 
700       if (C->getType() == llvm::Type::Int1Ty) {
701         const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
702         C = VMContext.getConstantExprZExt(C, BoolTy);
703       }
704       return C;
705     }
706     case APValue::ComplexInt: {
707       llvm::Constant *Complex[2];
708 
709       Complex[0] = llvm::ConstantInt::get(VMContext,
710                                           Result.Val.getComplexIntReal());
711       Complex[1] = llvm::ConstantInt::get(VMContext,
712                                           Result.Val.getComplexIntImag());
713 
714       return VMContext.getConstantStruct(Complex, 2);
715     }
716     case APValue::Float:
717       return VMContext.getConstantFP(Result.Val.getFloat());
718     case APValue::ComplexFloat: {
719       llvm::Constant *Complex[2];
720 
721       Complex[0] = VMContext.getConstantFP(Result.Val.getComplexFloatReal());
722       Complex[1] = VMContext.getConstantFP(Result.Val.getComplexFloatImag());
723 
724       return VMContext.getConstantStruct(Complex, 2);
725     }
726     case APValue::Vector: {
727       llvm::SmallVector<llvm::Constant *, 4> Inits;
728       unsigned NumElts = Result.Val.getVectorLength();
729 
730       for (unsigned i = 0; i != NumElts; ++i) {
731         APValue &Elt = Result.Val.getVectorElt(i);
732         if (Elt.isInt())
733           Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
734         else
735           Inits.push_back(VMContext.getConstantFP(Elt.getFloat()));
736       }
737       return VMContext.getConstantVector(&Inits[0], Inits.size());
738     }
739     }
740   }
741 
742   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
743   if (C && C->getType() == llvm::Type::Int1Ty) {
744     const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
745     C = VMContext.getConstantExprZExt(C, BoolTy);
746   }
747   return C;
748 }
749 
750 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
751   // Always return an LLVM null constant for now; this will change when we
752   // get support for IRGen of member pointers.
753   return getLLVMContext().getNullValue(getTypes().ConvertType(T));
754 }
755