CGDecl.cpp revision 9c2f06b373e6209447baf1fd5a86dd6602c573a8
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 Alloc->setAlignment(getContext().getDeclAlignInBytes(&D)); 176 DeclPtr = Alloc; 177 } else { 178 // Targets that don't support recursion emit locals as globals. 179 const char *Class = 180 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto."; 181 DeclPtr = GenerateStaticBlockVarDecl(D, true, Class, 182 llvm::GlobalValue 183 ::InternalLinkage); 184 } 185 186 if (Ty->isVariablyModifiedType()) 187 EmitVLASize(Ty); 188 } else { 189 if (!DidCallStackSave) { 190 // Save the stack. 191 const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 192 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack"); 193 194 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 195 llvm::Value *V = Builder.CreateCall(F); 196 197 Builder.CreateStore(V, Stack); 198 199 DidCallStackSave = true; 200 201 { 202 // Push a cleanup block and restore the stack there. 203 CleanupScope scope(*this); 204 205 V = Builder.CreateLoad(Stack, "tmp"); 206 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 207 Builder.CreateCall(F, V); 208 } 209 } 210 211 // Get the element type. 212 const llvm::Type *LElemTy = ConvertType(Ty); 213 const llvm::Type *LElemPtrTy = 214 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace()); 215 216 llvm::Value *VLASize = EmitVLASize(Ty); 217 218 // Downcast the VLA size expression 219 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp"); 220 221 // Allocate memory for the array. 222 llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla"); 223 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp"); 224 } 225 226 llvm::Value *&DMEntry = LocalDeclMap[&D]; 227 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 228 DMEntry = DeclPtr; 229 230 // Emit debug info for local var declaration. 231 if (CGDebugInfo *DI = getDebugInfo()) { 232 DI->setLocation(D.getLocation()); 233 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 234 } 235 236 // If this local has an initializer, emit it now. 237 if (const Expr *Init = D.getInit()) { 238 if (!hasAggregateLLVMType(Init->getType())) { 239 llvm::Value *V = EmitScalarExpr(Init); 240 Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified()); 241 } else if (Init->getType()->isAnyComplexType()) { 242 EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified()); 243 } else { 244 EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified()); 245 } 246 } 247 248 // Handle the cleanup attribute 249 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 250 const FunctionDecl *FD = CA->getFunctionDecl(); 251 252 llvm::Constant* F = CGM.GetAddrOfFunction(FD); 253 assert(F && "Could not find function!"); 254 255 CleanupScope scope(*this); 256 257 CallArgList Args; 258 Args.push_back(std::make_pair(RValue::get(DeclPtr), 259 getContext().getPointerType(D.getType()))); 260 261 EmitCall(CGM.getTypes().getFunctionInfo(FD), F, Args); 262 } 263} 264 265/// Emit an alloca (or GlobalValue depending on target) 266/// for the specified parameter and set up LocalDeclMap. 267void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) { 268 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 269 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 270 "Invalid argument to EmitParmDecl"); 271 QualType Ty = D.getType(); 272 273 llvm::Value *DeclPtr; 274 if (!Ty->isConstantSizeType()) { 275 // Variable sized values always are passed by-reference. 276 DeclPtr = Arg; 277 } else if (Target.useGlobalsForAutomaticVariables()) { 278 // Targets that don't have stack use global address space for parameters. 279 // Specify external linkage for such globals so that llvm optimizer do 280 // not assume there values initialized as zero. 281 DeclPtr = GenerateStaticBlockVarDecl(D, true, ".auto.", 282 llvm::GlobalValue::ExternalLinkage); 283 } else { 284 // A fixed sized single-value variable becomes an alloca in the entry block. 285 const llvm::Type *LTy = ConvertType(Ty); 286 if (LTy->isSingleValueType()) { 287 // TODO: Alignment 288 std::string Name = D.getNameAsString(); 289 Name += ".addr"; 290 DeclPtr = CreateTempAlloca(LTy, Name.c_str()); 291 292 // Store the initial value into the alloca. 293 Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified()); 294 } else { 295 // Otherwise, if this is an aggregate, just use the input pointer. 296 DeclPtr = Arg; 297 } 298 Arg->setName(D.getNameAsString()); 299 } 300 301 llvm::Value *&DMEntry = LocalDeclMap[&D]; 302 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 303 DMEntry = DeclPtr; 304 305 // Emit debug info for param declaration. 306 if (CGDebugInfo *DI = getDebugInfo()) { 307 DI->setLocation(D.getLocation()); 308 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder); 309 } 310} 311 312