CGDecl.cpp revision 6ec3668a2608b63473207319f5ceff9bbd22ea51
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 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 Decl nodes as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CGDebugInfo.h" 15#include "CodeGenFunction.h" 16#include "CodeGenModule.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/Decl.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/Basic/SourceManager.h" 21#include "clang/Basic/TargetInfo.h" 22#include "llvm/GlobalVariable.h" 23#include "llvm/Intrinsics.h" 24#include "llvm/Type.h" 25using namespace clang; 26using namespace CodeGen; 27 28 29void CodeGenFunction::EmitDecl(const Decl &D) { 30 switch (D.getKind()) { 31 default: assert(0 && "Unknown decl kind!"); 32 case Decl::ParmVar: 33 assert(0 && "Parmdecls should not be in declstmts!"); 34 case Decl::Function: // void X(); 35 case Decl::Record: // struct/union/class X; 36 case Decl::Enum: // enum X; 37 case Decl::EnumConstant: // enum ? { X = ? } 38 case Decl::CXXRecord: // struct/union/class X; [C++] 39 // None of these decls require codegen support. 40 return; 41 42 case Decl::Var: { 43 const VarDecl &VD = cast<VarDecl>(D); 44 assert(VD.isBlockVarDecl() && 45 "Should not see file-scope variables inside a function!"); 46 return EmitBlockVarDecl(VD); 47 } 48 49 case Decl::Typedef: { // typedef int X; 50 const TypedefDecl &TD = cast<TypedefDecl>(D); 51 QualType Ty = TD.getUnderlyingType(); 52 53 if (Ty->isVariablyModifiedType()) 54 EmitVLASize(Ty); 55 } 56 } 57} 58 59/// EmitBlockVarDecl - This method handles emission of any variable declaration 60/// inside a function, including static vars etc. 61void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) { 62 switch (D.getStorageClass()) { 63 case VarDecl::Static: 64 return EmitStaticBlockVarDecl(D); 65 case VarDecl::Extern: 66 // Don't emit it now, allow it to be emitted lazily on its first use. 67 return; 68 default: 69 assert((D.getStorageClass() == VarDecl::None || 70 D.getStorageClass() == VarDecl::Auto || 71 D.getStorageClass() == VarDecl::Register) && 72 "Unknown storage class"); 73 return EmitLocalBlockVarDecl(D); 74 } 75} 76 77llvm::GlobalValue * 78CodeGenFunction::GenerateStaticBlockVarDecl(const VarDecl &D, 79 bool NoInit, 80 const char *Separator, 81 llvm::GlobalValue 82 ::LinkageTypes Linkage) { 83 QualType Ty = D.getType(); 84 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 85 86 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty); 87 llvm::Constant *Init = 0; 88 if ((D.getInit() == 0) || NoInit) { 89 Init = llvm::Constant::getNullValue(LTy); 90 } else { 91 Init = CGM.EmitConstantExpr(D.getInit(), this); 92 93 // If constant emission failed, then this should be a C++ static 94 // initializer. 95 if (!Init) { 96 if (!getContext().getLangOptions().CPlusPlus) { 97 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 98 Init = llvm::Constant::getNullValue(LTy); 99 } else { 100 return GenerateStaticCXXBlockVarDecl(D); 101 } 102 } 103 } 104 105 assert(Init && "Unable to create initialiser for static decl"); 106 107 std::string ContextName; 108 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) 109 ContextName = CGM.getMangledName(FD); 110 else if (isa<ObjCMethodDecl>(CurFuncDecl)) 111 ContextName = std::string(CurFn->getNameStart(), 112 CurFn->getNameStart() + CurFn->getNameLen()); 113 else 114 assert(0 && "Unknown context for block var decl"); 115 116 llvm::GlobalValue *GV = 117 new llvm::GlobalVariable(Init->getType(), Ty.isConstant(getContext()), 118 Linkage, 119 Init, ContextName + Separator +D.getNameAsString(), 120 &CGM.getModule(), 0, Ty.getAddressSpace()); 121 122 return GV; 123} 124 125void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) { 126 127 llvm::Value *&DMEntry = LocalDeclMap[&D]; 128 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 129 130 llvm::GlobalValue *GV; 131 GV = GenerateStaticBlockVarDecl(D, false, ".", 132 llvm::GlobalValue::InternalLinkage); 133 134 // FIXME: Merge attribute handling. 135 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) { 136 SourceManager &SM = CGM.getContext().getSourceManager(); 137 llvm::Constant *Ann = 138 CGM.EmitAnnotateAttr(GV, AA, 139 SM.getInstantiationLineNumber(D.getLocation())); 140 CGM.AddAnnotation(Ann); 141 } 142 143 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 144 GV->setSection(SA->getName()); 145 146 if (D.getAttr<UsedAttr>()) 147 CGM.AddUsedGlobal(GV); 148 149 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType()); 150 const llvm::Type *LPtrTy = 151 llvm::PointerType::get(LTy, D.getType().getAddressSpace()); 152 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy); 153 154 // Emit global variable debug descriptor for static vars. 155 CGDebugInfo *DI = getDebugInfo(); 156 if(DI) { 157 DI->setLocation(D.getLocation()); 158 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D); 159 } 160} 161 162/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a 163/// variable declaration with auto, register, or no storage class specifier. 164/// These turn into simple stack objects, or GlobalValues depending on target. 165void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) { 166 QualType Ty = D.getType(); 167 168 llvm::Value *DeclPtr; 169 if (Ty->isConstantSizeType()) { 170 if (!Target.useGlobalsForAutomaticVariables()) { 171 // A normal fixed sized variable becomes an alloca in the entry block. 172 const llvm::Type *LTy = ConvertType(Ty); 173 llvm::AllocaInst *Alloc = 174 CreateTempAlloca(LTy, CGM.getMangledName(&D)); 175 unsigned align = getContext().getTypeAlign(Ty); 176 if (const AlignedAttr* AA = D.getAttr<AlignedAttr>()) 177 align = std::max(align, AA->getAlignment()); 178 Alloc->setAlignment(align >> 3); 179 DeclPtr = Alloc; 180 } else { 181 // Targets that don't support recursion emit locals as globals. 182 const char *Class = 183 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto."; 184 DeclPtr = GenerateStaticBlockVarDecl(D, true, Class, 185 llvm::GlobalValue 186 ::InternalLinkage); 187 } 188 189 if (Ty->isVariablyModifiedType()) 190 EmitVLASize(Ty); 191 } else { 192 if (!DidCallStackSave) { 193 // Save the stack. 194 const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 195 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack"); 196 197 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 198 llvm::Value *V = Builder.CreateCall(F); 199 200 Builder.CreateStore(V, Stack); 201 202 DidCallStackSave = true; 203 204 { 205 // Push a cleanup block and restore the stack there. 206 CleanupScope scope(*this); 207 208 V = Builder.CreateLoad(Stack, "tmp"); 209 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 210 Builder.CreateCall(F, V); 211 } 212 } 213 214 // Get the element type. 215 const llvm::Type *LElemTy = ConvertType(Ty); 216 const llvm::Type *LElemPtrTy = 217 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace()); 218 219 llvm::Value *VLASize = EmitVLASize(Ty); 220 221 // Downcast the VLA size expression 222 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp"); 223 224 // Allocate memory for the array. 225 llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla"); 226 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp"); 227 } 228 229 llvm::Value *&DMEntry = LocalDeclMap[&D]; 230 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 231 DMEntry = DeclPtr; 232 233 // Emit debug info for local var declaration. 234 if (CGDebugInfo *DI = getDebugInfo()) { 235 DI->setLocation(D.getLocation()); 236 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 237 } 238 239 // If this local has an initializer, emit it now. 240 if (const Expr *Init = D.getInit()) { 241 if (!hasAggregateLLVMType(Init->getType())) { 242 llvm::Value *V = EmitScalarExpr(Init); 243 Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified()); 244 } else if (Init->getType()->isAnyComplexType()) { 245 EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified()); 246 } else { 247 EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified()); 248 } 249 } 250 251 // Handle the cleanup attribute 252 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 253 const FunctionDecl *FD = CA->getFunctionDecl(); 254 255 llvm::Constant* F = CGM.GetAddrOfFunction(FD); 256 assert(F && "Could not find function!"); 257 258 CleanupScope scope(*this); 259 260 CallArgList Args; 261 Args.push_back(std::make_pair(RValue::get(DeclPtr), 262 getContext().getPointerType(D.getType()))); 263 264 EmitCall(CGM.getTypes().getFunctionInfo(FD), F, Args); 265 } 266} 267 268/// Emit an alloca (or GlobalValue depending on target) 269/// for the specified parameter and set up LocalDeclMap. 270void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) { 271 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 272 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 273 "Invalid argument to EmitParmDecl"); 274 QualType Ty = D.getType(); 275 276 llvm::Value *DeclPtr; 277 if (!Ty->isConstantSizeType()) { 278 // Variable sized values always are passed by-reference. 279 DeclPtr = Arg; 280 } else if (Target.useGlobalsForAutomaticVariables()) { 281 // Targets that don't have stack use global address space for parameters. 282 // Specify external linkage for such globals so that llvm optimizer do 283 // not assume there values initialized as zero. 284 DeclPtr = GenerateStaticBlockVarDecl(D, true, ".auto.", 285 llvm::GlobalValue::ExternalLinkage); 286 } else { 287 // A fixed sized single-value variable becomes an alloca in the entry block. 288 const llvm::Type *LTy = ConvertType(Ty); 289 if (LTy->isSingleValueType()) { 290 // TODO: Alignment 291 std::string Name = D.getNameAsString(); 292 Name += ".addr"; 293 DeclPtr = CreateTempAlloca(LTy, Name.c_str()); 294 295 // Store the initial value into the alloca. 296 Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified()); 297 } else { 298 // Otherwise, if this is an aggregate, just use the input pointer. 299 DeclPtr = Arg; 300 } 301 Arg->setName(D.getNameAsString()); 302 } 303 304 llvm::Value *&DMEntry = LocalDeclMap[&D]; 305 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 306 DMEntry = DeclPtr; 307 308 // Emit debug info for param declaration. 309 if (CGDebugInfo *DI = getDebugInfo()) { 310 DI->setLocation(D.getLocation()); 311 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder); 312 } 313} 314 315