1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Constant Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
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/StmtVisitor.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Target/TargetData.h"
25 using namespace clang;
26 using namespace CodeGen;
29 class VISIBILITY_HIDDEN ConstExprEmitter :
30 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
34 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
35 : CGM(cgm), CGF(cgf) {
38 //===--------------------------------------------------------------------===//
40 //===--------------------------------------------------------------------===//
42 llvm::Constant *VisitStmt(Stmt *S) {
46 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
47 return Visit(PE->getSubExpr());
50 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
51 return Visit(E->getInitializer());
54 llvm::Constant *VisitCastExpr(CastExpr* E) {
55 // GCC cast to union extension
56 if (E->getType()->isUnionType()) {
57 const llvm::Type *Ty = ConvertType(E->getType());
58 Expr *SubExpr = E->getSubExpr();
59 return EmitUnion(CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF),
62 // Explicit and implicit no-op casts
63 QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType();
64 if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy)) {
65 return Visit(E->getSubExpr());
70 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
71 return Visit(DAE->getExpr());
74 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
75 std::vector<llvm::Constant*> Elts;
76 const llvm::ArrayType *AType =
77 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
78 unsigned NumInitElements = ILE->getNumInits();
79 // FIXME: Check for wide strings
80 // FIXME: Check for NumInitElements exactly equal to 1??
81 if (NumInitElements > 0 &&
82 (isa<StringLiteral>(ILE->getInit(0)) ||
83 isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
84 ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
85 return Visit(ILE->getInit(0));
86 const llvm::Type *ElemTy = AType->getElementType();
87 unsigned NumElements = AType->getNumElements();
89 // Initialising an array requires us to automatically
90 // initialise any elements that have not been initialised explicitly
91 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
93 // Copy initializer elements.
95 bool RewriteType = false;
96 for (; i < NumInitableElts; ++i) {
97 Expr *Init = ILE->getInit(i);
98 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
101 RewriteType |= (C->getType() != ElemTy);
105 // Initialize remaining array elements.
106 // FIXME: This doesn't handle member pointers correctly!
107 for (; i < NumElements; ++i)
108 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
111 // FIXME: Try to avoid packing the array
112 std::vector<const llvm::Type*> Types;
113 for (unsigned i = 0; i < Elts.size(); ++i)
114 Types.push_back(Elts[i]->getType());
115 const llvm::StructType *SType = llvm::StructType::get(Types, true);
116 return llvm::ConstantStruct::get(SType, Elts);
119 return llvm::ConstantArray::get(AType, Elts);
122 void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts,
123 FieldDecl* Field, Expr* E) {
124 // Calculate the value to insert
125 llvm::Constant *C = CGM.EmitConstantExpr(E, Field->getType(), CGF);
129 llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
131 CGM.ErrorUnsupported(E, "bitfield initialization");
134 llvm::APInt V = CI->getValue();
136 // Calculate information about the relevant field
137 const llvm::Type* Ty = CI->getType();
138 const llvm::TargetData &TD = CGM.getTypes().getTargetData();
139 unsigned size = TD.getTypeAllocSizeInBits(Ty);
140 unsigned fieldOffset = CGM.getTypes().getLLVMFieldNo(Field) * size;
141 CodeGenTypes::BitFieldInfo bitFieldInfo =
142 CGM.getTypes().getBitFieldInfo(Field);
143 fieldOffset += bitFieldInfo.Begin;
145 // Find where to start the insertion
146 // FIXME: This is O(n^2) in the number of bit-fields!
147 // FIXME: This won't work if the struct isn't completely packed!
148 unsigned offset = 0, i = 0;
149 while (offset < (fieldOffset & -8))
150 offset += TD.getTypeAllocSizeInBits(Elts[i++]->getType());
152 // Advance over 0 sized elements (must terminate in bounds since
153 // the bitfield must have a size).
154 while (TD.getTypeAllocSizeInBits(Elts[i]->getType()) == 0)
157 // Promote the size of V if necessary
158 // FIXME: This should never occur, but currently it can because initializer
159 // constants are cast to bool, and because clang is not enforcing bitfield
161 if (bitFieldInfo.Size > V.getBitWidth())
162 V.zext(bitFieldInfo.Size);
164 // Insert the bits into the struct
165 // FIXME: This algorthm is only correct on X86!
166 // FIXME: THis algorthm assumes bit-fields only have byte-size elements!
167 unsigned bitsToInsert = bitFieldInfo.Size;
168 unsigned curBits = std::min(8 - (fieldOffset & 7), bitsToInsert);
169 unsigned byte = V.getLoBits(curBits).getZExtValue() << (fieldOffset & 7);
171 llvm::Constant* byteC = llvm::ConstantInt::get(llvm::Type::Int8Ty, byte);
172 Elts[i] = llvm::ConstantExpr::getOr(Elts[i], byteC);
175 bitsToInsert -= curBits;
180 curBits = bitsToInsert > 8 ? 8 : bitsToInsert;
181 byte = V.getLoBits(curBits).getZExtValue();
185 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
186 const llvm::StructType *SType =
187 cast<llvm::StructType>(ConvertType(ILE->getType()));
188 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
189 std::vector<llvm::Constant*> Elts;
191 // Initialize the whole structure to zero.
192 // FIXME: This doesn't handle member pointers correctly!
193 for (unsigned i = 0; i < SType->getNumElements(); ++i) {
194 const llvm::Type *FieldTy = SType->getElementType(i);
195 Elts.push_back(llvm::Constant::getNullValue(FieldTy));
198 // Copy initializer elements. Skip padding fields.
199 unsigned EltNo = 0; // Element no in ILE
200 int FieldNo = 0; // Field no in RecordDecl
201 bool RewriteType = false;
202 for (RecordDecl::field_iterator Field = RD->field_begin(CGM.getContext()),
203 FieldEnd = RD->field_end(CGM.getContext());
204 EltNo < ILE->getNumInits() && Field != FieldEnd; ++Field) {
206 if (!Field->getIdentifier())
209 if (Field->isBitField()) {
210 InsertBitfieldIntoStruct(Elts, *Field, ILE->getInit(EltNo));
212 unsigned FieldNo = CGM.getTypes().getLLVMFieldNo(*Field);
213 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(EltNo),
214 Field->getType(), CGF);
216 RewriteType |= (C->getType() != Elts[FieldNo]->getType());
223 // FIXME: Make this work for non-packed structs
224 assert(SType->isPacked() && "Cannot recreate unpacked structs");
225 std::vector<const llvm::Type*> Types;
226 for (unsigned i = 0; i < Elts.size(); ++i)
227 Types.push_back(Elts[i]->getType());
228 SType = llvm::StructType::get(Types, true);
231 return llvm::ConstantStruct::get(SType, Elts);
234 llvm::Constant *EmitUnion(llvm::Constant *C, const llvm::Type *Ty) {
238 // Build a struct with the union sub-element as the first member,
239 // and padded to the appropriate size
240 std::vector<llvm::Constant*> Elts;
241 std::vector<const llvm::Type*> Types;
243 Types.push_back(C->getType());
244 unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
245 unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty);
246 while (CurSize < TotalSize) {
247 Elts.push_back(llvm::Constant::getNullValue(llvm::Type::Int8Ty));
248 Types.push_back(llvm::Type::Int8Ty);
252 // This always generates a packed struct
253 // FIXME: Try to generate an unpacked struct when we can
254 llvm::StructType* STy = llvm::StructType::get(Types, true);
255 return llvm::ConstantStruct::get(STy, Elts);
258 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
259 const llvm::Type *Ty = ConvertType(ILE->getType());
261 FieldDecl* curField = ILE->getInitializedFieldInUnion();
263 // There's no field to initialize, so value-initialize the union.
265 // Make sure that it's really an empty and not a failure of
266 // semantic analysis.
267 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
268 for (RecordDecl::field_iterator Field = RD->field_begin(CGM.getContext()),
269 FieldEnd = RD->field_end(CGM.getContext());
270 Field != FieldEnd; ++Field)
271 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
273 return llvm::Constant::getNullValue(Ty);
276 if (curField->isBitField()) {
277 // Create a dummy struct for bit-field insertion
278 unsigned NumElts = CGM.getTargetData().getTypeAllocSize(Ty);
279 llvm::Constant* NV = llvm::Constant::getNullValue(llvm::Type::Int8Ty);
280 std::vector<llvm::Constant*> Elts(NumElts, NV);
282 InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0));
283 const llvm::ArrayType *RetTy =
284 llvm::ArrayType::get(NV->getType(), NumElts);
285 return llvm::ConstantArray::get(RetTy, Elts);
288 llvm::Constant *InitElem;
289 if (ILE->getNumInits() > 0) {
290 Expr *Init = ILE->getInit(0);
291 InitElem = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
293 InitElem = CGM.EmitNullConstant(curField->getType());
295 return EmitUnion(InitElem, Ty);
298 llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
299 const llvm::VectorType *VType =
300 cast<llvm::VectorType>(ConvertType(ILE->getType()));
301 const llvm::Type *ElemTy = VType->getElementType();
302 std::vector<llvm::Constant*> Elts;
303 unsigned NumElements = VType->getNumElements();
304 unsigned NumInitElements = ILE->getNumInits();
306 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
308 // Copy initializer elements.
310 for (; i < NumInitableElts; ++i) {
311 Expr *Init = ILE->getInit(i);
312 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
318 for (; i < NumElements; ++i)
319 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
321 return llvm::ConstantVector::get(VType, Elts);
324 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
325 return CGM.EmitNullConstant(E->getType());
328 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
329 if (ILE->getType()->isScalarType()) {
330 // We have a scalar in braces. Just use the first element.
331 if (ILE->getNumInits() > 0) {
332 Expr *Init = ILE->getInit(0);
333 return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
335 return CGM.EmitNullConstant(ILE->getType());
338 if (ILE->getType()->isArrayType())
339 return EmitArrayInitialization(ILE);
341 if (ILE->getType()->isStructureType())
342 return EmitStructInitialization(ILE);
344 if (ILE->getType()->isUnionType())
345 return EmitUnionInitialization(ILE);
347 if (ILE->getType()->isVectorType())
348 return EmitVectorInitialization(ILE);
350 assert(0 && "Unable to handle InitListExpr");
351 // Get rid of control reaches end of void function warning.
356 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
357 assert(!E->getType()->isPointerType() && "Strings are always arrays");
359 // This must be a string initializing an array in a static initializer.
360 // Don't emit it as the address of the string, emit the string data itself
361 // as an inline array.
362 return llvm::ConstantArray::get(CGM.GetStringForStringLiteral(E), false);
365 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
366 // This must be an @encode initializing an array in a static initializer.
367 // Don't emit it as the address of the string, emit the string data itself
368 // as an inline array.
370 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
371 const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
373 // Resize the string to the right size, adding zeros at the end, or
374 // truncating as needed.
375 Str.resize(CAT->getSize().getZExtValue(), '\0');
376 return llvm::ConstantArray::get(Str, false);
379 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
380 return Visit(E->getSubExpr());
384 const llvm::Type *ConvertType(QualType T) {
385 return CGM.getTypes().ConvertType(T);
389 llvm::Constant *EmitLValue(Expr *E) {
390 switch (E->getStmtClass()) {
392 case Expr::CompoundLiteralExprClass: {
393 // Note that due to the nature of compound literals, this is guaranteed
394 // to be the only use of the variable, so we just generate it here.
395 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
396 llvm::Constant* C = Visit(CLE->getInitializer());
397 // FIXME: "Leaked" on failure.
399 C = new llvm::GlobalVariable(C->getType(),
400 E->getType().isConstQualified(),
401 llvm::GlobalValue::InternalLinkage,
402 C, ".compoundliteral", &CGM.getModule());
405 case Expr::DeclRefExprClass:
406 case Expr::QualifiedDeclRefExprClass: {
407 NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
408 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
409 return CGM.GetAddrOfFunction(GlobalDecl(FD));
410 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
411 // We can never refer to a variable with local storage.
412 if (!VD->hasLocalStorage()) {
413 if (VD->isFileVarDecl() || VD->hasExternalStorage())
414 return CGM.GetAddrOfGlobalVar(VD);
415 else if (VD->isBlockVarDecl()) {
416 assert(CGF && "Can't access static local vars without CGF");
417 return CGF->GetAddrOfStaticLocalVar(VD);
423 case Expr::StringLiteralClass:
424 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
425 case Expr::ObjCEncodeExprClass:
426 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
427 case Expr::ObjCStringLiteralClass: {
428 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
429 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL);
430 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
432 case Expr::PredefinedExprClass: {
433 // __func__/__FUNCTION__ -> "". __PRETTY_FUNCTION__ -> "top level".
435 if (cast<PredefinedExpr>(E)->getIdentType() ==
436 PredefinedExpr::PrettyFunction)
439 return CGM.GetAddrOfConstantCString(Str, ".tmp");
441 case Expr::AddrLabelExprClass: {
442 assert(CGF && "Invalid address of label expression outside function.");
443 unsigned id = CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
444 llvm::Constant *C = llvm::ConstantInt::get(llvm::Type::Int32Ty, id);
445 return llvm::ConstantExpr::getIntToPtr(C, ConvertType(E->getType()));
447 case Expr::CallExprClass: {
448 CallExpr* CE = cast<CallExpr>(E);
449 if (CE->isBuiltinCall(CGM.getContext()) !=
450 Builtin::BI__builtin___CFStringMakeConstantString)
452 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
453 const StringLiteral *Literal = cast<StringLiteral>(Arg);
454 // FIXME: need to deal with UCN conversion issues.
455 return CGM.GetAddrOfConstantCFString(Literal);
457 case Expr::BlockExprClass: {
458 std::string FunctionName;
460 FunctionName = CGF->CurFn->getName();
462 FunctionName = "global";
464 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
472 } // end anonymous namespace.
474 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
476 CodeGenFunction *CGF) {
477 Expr::EvalResult Result;
479 bool Success = false;
481 if (DestType->isReferenceType())
482 Success = E->EvaluateAsLValue(Result, Context);
484 Success = E->Evaluate(Result, Context);
487 assert(!Result.HasSideEffects &&
488 "Constant expr should not have any side effects!");
489 switch (Result.Val.getKind()) {
490 case APValue::Uninitialized:
491 assert(0 && "Constant expressions should be initialized.");
493 case APValue::LValue: {
494 const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
495 llvm::Constant *Offset =
496 llvm::ConstantInt::get(llvm::Type::Int64Ty,
497 Result.Val.getLValueOffset());
500 if (const Expr *LVBase = Result.Val.getLValueBase()) {
501 C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
503 // Apply offset if necessary.
504 if (!Offset->isNullValue()) {
505 const llvm::Type *Type =
506 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
507 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
508 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1);
509 C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
512 // Convert to the appropriate type; this could be an lvalue for
514 if (isa<llvm::PointerType>(DestTy))
515 return llvm::ConstantExpr::getBitCast(C, DestTy);
517 return llvm::ConstantExpr::getPtrToInt(C, DestTy);
521 // Convert to the appropriate type; this could be an lvalue for
523 if (isa<llvm::PointerType>(DestTy))
524 return llvm::ConstantExpr::getIntToPtr(C, DestTy);
526 // If the types don't match this should only be a truncate.
527 if (C->getType() != DestTy)
528 return llvm::ConstantExpr::getTrunc(C, DestTy);
534 llvm::Constant *C = llvm::ConstantInt::get(Result.Val.getInt());
536 if (C->getType() == llvm::Type::Int1Ty) {
537 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
538 C = llvm::ConstantExpr::getZExt(C, BoolTy);
542 case APValue::ComplexInt: {
543 llvm::Constant *Complex[2];
545 Complex[0] = llvm::ConstantInt::get(Result.Val.getComplexIntReal());
546 Complex[1] = llvm::ConstantInt::get(Result.Val.getComplexIntImag());
548 return llvm::ConstantStruct::get(Complex, 2);
551 return llvm::ConstantFP::get(Result.Val.getFloat());
552 case APValue::ComplexFloat: {
553 llvm::Constant *Complex[2];
555 Complex[0] = llvm::ConstantFP::get(Result.Val.getComplexFloatReal());
556 Complex[1] = llvm::ConstantFP::get(Result.Val.getComplexFloatImag());
558 return llvm::ConstantStruct::get(Complex, 2);
560 case APValue::Vector: {
561 llvm::SmallVector<llvm::Constant *, 4> Inits;
562 unsigned NumElts = Result.Val.getVectorLength();
564 for (unsigned i = 0; i != NumElts; ++i) {
565 APValue &Elt = Result.Val.getVectorElt(i);
567 Inits.push_back(llvm::ConstantInt::get(Elt.getInt()));
569 Inits.push_back(llvm::ConstantFP::get(Elt.getFloat()));
571 return llvm::ConstantVector::get(&Inits[0], Inits.size());
576 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
577 if (C && C->getType() == llvm::Type::Int1Ty) {
578 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
579 C = llvm::ConstantExpr::getZExt(C, BoolTy);
584 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
585 // Always return an LLVM null constant for now; this will change when we
586 // get support for IRGen of member pointers.
587 return llvm::Constant::getNullValue(getTypes().ConvertType(T));