1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===// 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 is the internal per-translation-unit state used for llvm translation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef CLANG_CODEGEN_CODEGENMODULE_H 15 #define CLANG_CODEGEN_CODEGENMODULE_H 16 17 #include "clang/Basic/ABI.h" 18 #include "clang/Basic/LangOptions.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/GlobalDecl.h" 23 #include "clang/AST/Mangle.h" 24 #include "CGVTables.h" 25 #include "CodeGenTypes.h" 26 #include "llvm/Module.h" 27 #include "llvm/ADT/DenseMap.h" 28 #include "llvm/ADT/StringMap.h" 29 #include "llvm/ADT/StringSet.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/Support/ValueHandle.h" 32 33 namespace llvm { 34 class Module; 35 class Constant; 36 class ConstantInt; 37 class Function; 38 class GlobalValue; 39 class TargetData; 40 class FunctionType; 41 class LLVMContext; 42 } 43 44 namespace clang { 45 class TargetCodeGenInfo; 46 class ASTContext; 47 class FunctionDecl; 48 class IdentifierInfo; 49 class ObjCMethodDecl; 50 class ObjCImplementationDecl; 51 class ObjCCategoryImplDecl; 52 class ObjCProtocolDecl; 53 class ObjCEncodeExpr; 54 class BlockExpr; 55 class CharUnits; 56 class Decl; 57 class Expr; 58 class Stmt; 59 class StringLiteral; 60 class NamedDecl; 61 class ValueDecl; 62 class VarDecl; 63 class LangOptions; 64 class CodeGenOptions; 65 class Diagnostic; 66 class AnnotateAttr; 67 class CXXDestructorDecl; 68 class MangleBuffer; 69 70 namespace CodeGen { 71 72 class CallArgList; 73 class CodeGenFunction; 74 class CodeGenTBAA; 75 class CGCXXABI; 76 class CGDebugInfo; 77 class CGObjCRuntime; 78 class BlockFieldFlags; 79 class FunctionArgList; 80 81 struct OrderGlobalInits { 82 unsigned int priority; 83 unsigned int lex_order; 84 OrderGlobalInits(unsigned int p, unsigned int l) 85 : priority(p), lex_order(l) {} 86 87 bool operator==(const OrderGlobalInits &RHS) const { 88 return priority == RHS.priority && 89 lex_order == RHS.lex_order; 90 } 91 92 bool operator<(const OrderGlobalInits &RHS) const { 93 if (priority < RHS.priority) 94 return true; 95 96 return priority == RHS.priority && lex_order < RHS.lex_order; 97 } 98 }; 99 100 struct CodeGenTypeCache { 101 /// void 102 llvm::Type *VoidTy; 103 104 /// i8, i32, and i64 105 llvm::IntegerType *Int8Ty, *Int32Ty, *Int64Ty; 106 107 /// int 108 llvm::IntegerType *IntTy; 109 110 /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size. 111 union { 112 llvm::IntegerType *IntPtrTy; 113 llvm::IntegerType *SizeTy; 114 llvm::IntegerType *PtrDiffTy; 115 }; 116 117 /// void* in address space 0 118 union { 119 llvm::PointerType *VoidPtrTy; 120 llvm::PointerType *Int8PtrTy; 121 }; 122 123 /// void** in address space 0 124 union { 125 llvm::PointerType *VoidPtrPtrTy; 126 llvm::PointerType *Int8PtrPtrTy; 127 }; 128 129 /// The width of a pointer into the generic address space. 130 unsigned char PointerWidthInBits; 131 132 /// The size and alignment of a pointer into the generic address 133 /// space. 134 union { 135 unsigned char PointerAlignInBytes; 136 unsigned char PointerSizeInBytes; 137 }; 138 }; 139 140 struct RREntrypoints { 141 RREntrypoints() { memset(this, 0, sizeof(*this)); } 142 /// void objc_autoreleasePoolPop(void*); 143 llvm::Constant *objc_autoreleasePoolPop; 144 145 /// void *objc_autoreleasePoolPush(void); 146 llvm::Constant *objc_autoreleasePoolPush; 147 }; 148 149 struct ARCEntrypoints { 150 ARCEntrypoints() { memset(this, 0, sizeof(*this)); } 151 152 /// id objc_autorelease(id); 153 llvm::Constant *objc_autorelease; 154 155 /// id objc_autoreleaseReturnValue(id); 156 llvm::Constant *objc_autoreleaseReturnValue; 157 158 /// void objc_copyWeak(id *dest, id *src); 159 llvm::Constant *objc_copyWeak; 160 161 /// void objc_destroyWeak(id*); 162 llvm::Constant *objc_destroyWeak; 163 164 /// id objc_initWeak(id*, id); 165 llvm::Constant *objc_initWeak; 166 167 /// id objc_loadWeak(id*); 168 llvm::Constant *objc_loadWeak; 169 170 /// id objc_loadWeakRetained(id*); 171 llvm::Constant *objc_loadWeakRetained; 172 173 /// void objc_moveWeak(id *dest, id *src); 174 llvm::Constant *objc_moveWeak; 175 176 /// id objc_retain(id); 177 llvm::Constant *objc_retain; 178 179 /// id objc_retainAutorelease(id); 180 llvm::Constant *objc_retainAutorelease; 181 182 /// id objc_retainAutoreleaseReturnValue(id); 183 llvm::Constant *objc_retainAutoreleaseReturnValue; 184 185 /// id objc_retainAutoreleasedReturnValue(id); 186 llvm::Constant *objc_retainAutoreleasedReturnValue; 187 188 /// id objc_retainBlock(id); 189 llvm::Constant *objc_retainBlock; 190 191 /// void objc_release(id); 192 llvm::Constant *objc_release; 193 194 /// id objc_storeStrong(id*, id); 195 llvm::Constant *objc_storeStrong; 196 197 /// id objc_storeWeak(id*, id); 198 llvm::Constant *objc_storeWeak; 199 200 /// A void(void) inline asm to use to mark that the return value of 201 /// a call will be immediately retain. 202 llvm::InlineAsm *retainAutoreleasedReturnValueMarker; 203 }; 204 205 /// CodeGenModule - This class organizes the cross-function state that is used 206 /// while generating LLVM code. 207 class CodeGenModule : public CodeGenTypeCache { 208 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT 209 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT 210 211 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList; 212 213 ASTContext &Context; 214 const LangOptions &Features; 215 const CodeGenOptions &CodeGenOpts; 216 llvm::Module &TheModule; 217 const llvm::TargetData &TheTargetData; 218 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo; 219 Diagnostic &Diags; 220 CGCXXABI &ABI; 221 CodeGenTypes Types; 222 CodeGenTBAA *TBAA; 223 224 /// VTables - Holds information about C++ vtables. 225 CodeGenVTables VTables; 226 friend class CodeGenVTables; 227 228 CGObjCRuntime* ObjCRuntime; 229 CGDebugInfo* DebugInfo; 230 ARCEntrypoints *ARCData; 231 RREntrypoints *RRData; 232 233 // WeakRefReferences - A set of references that have only been seen via 234 // a weakref so far. This is used to remove the weak of the reference if we ever 235 // see a direct reference or a definition. 236 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences; 237 238 /// DeferredDecls - This contains all the decls which have definitions but 239 /// which are deferred for emission and therefore should only be output if 240 /// they are actually used. If a decl is in this, then it is known to have 241 /// not been referenced yet. 242 llvm::StringMap<GlobalDecl> DeferredDecls; 243 244 /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen 245 /// that *are* actually referenced. These get code generated when the module 246 /// is done. 247 std::vector<GlobalDecl> DeferredDeclsToEmit; 248 249 /// LLVMUsed - List of global values which are required to be 250 /// present in the object file; bitcast to i8*. This is used for 251 /// forcing visibility of symbols which may otherwise be optimized 252 /// out. 253 std::vector<llvm::WeakVH> LLVMUsed; 254 255 /// GlobalCtors - Store the list of global constructors and their respective 256 /// priorities to be emitted when the translation unit is complete. 257 CtorList GlobalCtors; 258 259 /// GlobalDtors - Store the list of global destructors and their respective 260 /// priorities to be emitted when the translation unit is complete. 261 CtorList GlobalDtors; 262 263 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names. 264 llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames; 265 llvm::BumpPtrAllocator MangledNamesAllocator; 266 267 /// Global annotations. 268 std::vector<llvm::Constant*> Annotations; 269 270 /// Map used to get unique annotation strings. 271 llvm::StringMap<llvm::Constant*> AnnotationStrings; 272 273 llvm::StringMap<llvm::Constant*> CFConstantStringMap; 274 llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap; 275 llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap; 276 277 /// CXXGlobalInits - Global variables with initializers that need to run 278 /// before main. 279 std::vector<llvm::Constant*> CXXGlobalInits; 280 281 /// When a C++ decl with an initializer is deferred, null is 282 /// appended to CXXGlobalInits, and the index of that null is placed 283 /// here so that the initializer will be performed in the correct 284 /// order. 285 llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; 286 287 /// - Global variables with initializers whose order of initialization 288 /// is set by init_priority attribute. 289 290 SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8> 291 PrioritizedCXXGlobalInits; 292 293 /// CXXGlobalDtors - Global destructor functions and arguments that need to 294 /// run on termination. 295 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors; 296 297 /// @name Cache for Objective-C runtime types 298 /// @{ 299 300 /// CFConstantStringClassRef - Cached reference to the class for constant 301 /// strings. This value has type int * but is actually an Obj-C class pointer. 302 llvm::Constant *CFConstantStringClassRef; 303 304 /// ConstantStringClassRef - Cached reference to the class for constant 305 /// strings. This value has type int * but is actually an Obj-C class pointer. 306 llvm::Constant *ConstantStringClassRef; 307 308 /// \brief The LLVM type corresponding to NSConstantString. 309 llvm::StructType *NSConstantStringType; 310 311 /// \brief The type used to describe the state of a fast enumeration in 312 /// Objective-C's for..in loop. 313 QualType ObjCFastEnumerationStateType; 314 315 /// @} 316 317 /// Lazily create the Objective-C runtime 318 void createObjCRuntime(); 319 320 llvm::LLVMContext &VMContext; 321 322 /// @name Cache for Blocks Runtime Globals 323 /// @{ 324 325 llvm::Constant *NSConcreteGlobalBlock; 326 llvm::Constant *NSConcreteStackBlock; 327 328 llvm::Constant *BlockObjectAssign; 329 llvm::Constant *BlockObjectDispose; 330 331 llvm::Type *BlockDescriptorType; 332 llvm::Type *GenericBlockLiteralType; 333 334 struct { 335 int GlobalUniqueCount; 336 } Block; 337 338 /// @} 339 public: 340 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts, 341 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags); 342 343 ~CodeGenModule(); 344 345 /// Release - Finalize LLVM code generation. 346 void Release(); 347 348 /// getObjCRuntime() - Return a reference to the configured 349 /// Objective-C runtime. 350 CGObjCRuntime &getObjCRuntime() { 351 if (!ObjCRuntime) createObjCRuntime(); 352 return *ObjCRuntime; 353 } 354 355 /// hasObjCRuntime() - Return true iff an Objective-C runtime has 356 /// been configured. 357 bool hasObjCRuntime() { return !!ObjCRuntime; } 358 359 /// getCXXABI() - Return a reference to the configured C++ ABI. 360 CGCXXABI &getCXXABI() { return ABI; } 361 362 ARCEntrypoints &getARCEntrypoints() const { 363 assert(getLangOptions().ObjCAutoRefCount && ARCData != 0); 364 return *ARCData; 365 } 366 367 RREntrypoints &getRREntrypoints() const { 368 assert(RRData != 0); 369 return *RRData; 370 } 371 372 llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) { 373 return StaticLocalDeclMap[VD]; 374 } 375 void setStaticLocalDeclAddress(const VarDecl *D, 376 llvm::GlobalVariable *GV) { 377 StaticLocalDeclMap[D] = GV; 378 } 379 380 CGDebugInfo *getModuleDebugInfo() { return DebugInfo; } 381 382 ASTContext &getContext() const { return Context; } 383 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } 384 const LangOptions &getLangOptions() const { return Features; } 385 llvm::Module &getModule() const { return TheModule; } 386 CodeGenTypes &getTypes() { return Types; } 387 CodeGenVTables &getVTables() { return VTables; } 388 Diagnostic &getDiags() const { return Diags; } 389 const llvm::TargetData &getTargetData() const { return TheTargetData; } 390 const TargetInfo &getTarget() const { return Context.getTargetInfo(); } 391 llvm::LLVMContext &getLLVMContext() { return VMContext; } 392 const TargetCodeGenInfo &getTargetCodeGenInfo(); 393 bool isTargetDarwin() const; 394 395 bool shouldUseTBAA() const { return TBAA != 0; } 396 397 llvm::MDNode *getTBAAInfo(QualType QTy); 398 399 static void DecorateInstruction(llvm::Instruction *Inst, 400 llvm::MDNode *TBAAInfo); 401 402 /// getSize - Emit the given number of characters as a value of type size_t. 403 llvm::ConstantInt *getSize(CharUnits numChars); 404 405 /// setGlobalVisibility - Set the visibility for the given LLVM 406 /// GlobalValue. 407 void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const; 408 409 /// TypeVisibilityKind - The kind of global variable that is passed to 410 /// setTypeVisibility 411 enum TypeVisibilityKind { 412 TVK_ForVTT, 413 TVK_ForVTable, 414 TVK_ForConstructionVTable, 415 TVK_ForRTTI, 416 TVK_ForRTTIName 417 }; 418 419 /// setTypeVisibility - Set the visibility for the given global 420 /// value which holds information about a type. 421 void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D, 422 TypeVisibilityKind TVK) const; 423 424 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) { 425 switch (V) { 426 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility; 427 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility; 428 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility; 429 } 430 llvm_unreachable("unknown visibility!"); 431 return llvm::GlobalValue::DefaultVisibility; 432 } 433 434 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) { 435 if (isa<CXXConstructorDecl>(GD.getDecl())) 436 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()), 437 GD.getCtorType()); 438 else if (isa<CXXDestructorDecl>(GD.getDecl())) 439 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()), 440 GD.getDtorType()); 441 else if (isa<FunctionDecl>(GD.getDecl())) 442 return GetAddrOfFunction(GD); 443 else 444 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 445 } 446 447 /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given 448 /// type. If a variable with a different type already exists then a new 449 /// variable with the right type will be created and all uses of the old 450 /// variable will be replaced with a bitcast to the new variable. 451 llvm::GlobalVariable * 452 CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, 453 llvm::GlobalValue::LinkageTypes Linkage); 454 455 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 456 /// given global variable. If Ty is non-null and if the global doesn't exist, 457 /// then it will be greated with the specified type instead of whatever the 458 /// normal requested type would be. 459 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D, 460 llvm::Type *Ty = 0); 461 462 463 /// GetAddrOfFunction - Return the address of the given function. If Ty is 464 /// non-null, then this function will use the specified type if it has to 465 /// create it. 466 llvm::Constant *GetAddrOfFunction(GlobalDecl GD, 467 llvm::Type *Ty = 0, 468 bool ForVTable = false); 469 470 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor 471 /// for the given type. 472 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false); 473 474 /// GetAddrOfThunk - Get the address of the thunk for the given global decl. 475 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk); 476 477 /// GetWeakRefReference - Get a reference to the target of VD. 478 llvm::Constant *GetWeakRefReference(const ValueDecl *VD); 479 480 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to 481 /// a class. Returns null if the offset is 0. 482 llvm::Constant * 483 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 484 CastExpr::path_const_iterator PathBegin, 485 CastExpr::path_const_iterator PathEnd); 486 487 /// A pair of helper functions for a __block variable. 488 class ByrefHelpers : public llvm::FoldingSetNode { 489 public: 490 llvm::Constant *CopyHelper; 491 llvm::Constant *DisposeHelper; 492 493 /// The alignment of the field. This is important because 494 /// different offsets to the field within the byref struct need to 495 /// have different helper functions. 496 CharUnits Alignment; 497 498 ByrefHelpers(CharUnits alignment) : Alignment(alignment) {} 499 virtual ~ByrefHelpers(); 500 501 void Profile(llvm::FoldingSetNodeID &id) const { 502 id.AddInteger(Alignment.getQuantity()); 503 profileImpl(id); 504 } 505 virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0; 506 507 virtual bool needsCopy() const { return true; } 508 virtual void emitCopy(CodeGenFunction &CGF, 509 llvm::Value *dest, llvm::Value *src) = 0; 510 511 virtual bool needsDispose() const { return true; } 512 virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0; 513 }; 514 515 llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache; 516 517 /// getUniqueBlockCount - Fetches the global unique block count. 518 int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } 519 520 /// getBlockDescriptorType - Fetches the type of a generic block 521 /// descriptor. 522 llvm::Type *getBlockDescriptorType(); 523 524 /// getGenericBlockLiteralType - The type of a generic block literal. 525 llvm::Type *getGenericBlockLiteralType(); 526 527 /// GetAddrOfGlobalBlock - Gets the address of a block which 528 /// requires no captures. 529 llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *); 530 531 /// GetStringForStringLiteral - Return the appropriate bytes for a string 532 /// literal, properly padded to match the literal type. If only the address of 533 /// a constant is needed consider using GetAddrOfConstantStringLiteral. 534 std::string GetStringForStringLiteral(const StringLiteral *E); 535 536 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object 537 /// for the given string. 538 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal); 539 540 /// GetAddrOfConstantString - Return a pointer to a constant NSString object 541 /// for the given string. Or a user defined String object as defined via 542 /// -fconstant-string-class=class_name option. 543 llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal); 544 545 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array 546 /// for the given string literal. 547 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S); 548 549 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 550 /// array for the given ObjCEncodeExpr node. 551 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *); 552 553 /// GetAddrOfConstantString - Returns a pointer to a character array 554 /// containing the literal. This contents are exactly that of the given 555 /// string, i.e. it will not be null terminated automatically; see 556 /// GetAddrOfConstantCString. Note that whether the result is actually a 557 /// pointer to an LLVM constant depends on Feature.WriteableStrings. 558 /// 559 /// The result has pointer to array type. 560 /// 561 /// \param GlobalName If provided, the name to use for the global 562 /// (if one is created). 563 llvm::Constant *GetAddrOfConstantString(StringRef Str, 564 const char *GlobalName=0, 565 unsigned Alignment=1); 566 567 /// GetAddrOfConstantCString - Returns a pointer to a character array 568 /// containing the literal and a terminating '\0' character. The result has 569 /// pointer to array type. 570 /// 571 /// \param GlobalName If provided, the name to use for the global (if one is 572 /// created). 573 llvm::Constant *GetAddrOfConstantCString(const std::string &str, 574 const char *GlobalName=0, 575 unsigned Alignment=1); 576 577 /// \brief Retrieve the record type that describes the state of an 578 /// Objective-C fast enumeration loop (for..in). 579 QualType getObjCFastEnumerationStateType(); 580 581 /// GetAddrOfCXXConstructor - Return the address of the constructor of the 582 /// given type. 583 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, 584 CXXCtorType ctorType, 585 const CGFunctionInfo *fnInfo = 0); 586 587 /// GetAddrOfCXXDestructor - Return the address of the constructor of the 588 /// given type. 589 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 590 CXXDtorType dtorType, 591 const CGFunctionInfo *fnInfo = 0); 592 593 /// getBuiltinLibFunction - Given a builtin id for a function like 594 /// "__builtin_fabsf", return a Function* for "fabsf". 595 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD, 596 unsigned BuiltinID); 597 598 llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = 599 ArrayRef<llvm::Type*>()); 600 601 /// EmitTopLevelDecl - Emit code for a single top level declaration. 602 void EmitTopLevelDecl(Decl *D); 603 604 /// AddUsedGlobal - Add a global which should be forced to be 605 /// present in the object file; these are emitted to the llvm.used 606 /// metadata global. 607 void AddUsedGlobal(llvm::GlobalValue *GV); 608 609 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global 610 /// destructor function. 611 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) { 612 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object)); 613 } 614 615 /// CreateRuntimeFunction - Create a new runtime function with the specified 616 /// type and name. 617 llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty, 618 StringRef Name, 619 llvm::Attributes ExtraAttrs = 620 llvm::Attribute::None); 621 /// CreateRuntimeVariable - Create a new runtime global variable with the 622 /// specified type and name. 623 llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty, 624 StringRef Name); 625 626 ///@name Custom Blocks Runtime Interfaces 627 ///@{ 628 629 llvm::Constant *getNSConcreteGlobalBlock(); 630 llvm::Constant *getNSConcreteStackBlock(); 631 llvm::Constant *getBlockObjectAssign(); 632 llvm::Constant *getBlockObjectDispose(); 633 634 ///@} 635 636 // UpdateCompleteType - Make sure that this type is translated. 637 void UpdateCompletedType(const TagDecl *TD); 638 639 llvm::Constant *getMemberPointerConstant(const UnaryOperator *e); 640 641 /// EmitConstantExpr - Try to emit the given expression as a 642 /// constant; returns 0 if the expression cannot be emitted as a 643 /// constant. 644 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType, 645 CodeGenFunction *CGF = 0); 646 647 /// EmitNullConstant - Return the result of value-initializing the given 648 /// type, i.e. a null expression of the given type. This is usually, 649 /// but not always, an LLVM null constant. 650 llvm::Constant *EmitNullConstant(QualType T); 651 652 /// Error - Emit a general error that something can't be done. 653 void Error(SourceLocation loc, StringRef error); 654 655 /// ErrorUnsupported - Print out an error that codegen doesn't support the 656 /// specified stmt yet. 657 /// \param OmitOnError - If true, then this error should only be emitted if no 658 /// other errors have been reported. 659 void ErrorUnsupported(const Stmt *S, const char *Type, 660 bool OmitOnError=false); 661 662 /// ErrorUnsupported - Print out an error that codegen doesn't support the 663 /// specified decl yet. 664 /// \param OmitOnError - If true, then this error should only be emitted if no 665 /// other errors have been reported. 666 void ErrorUnsupported(const Decl *D, const char *Type, 667 bool OmitOnError=false); 668 669 /// SetInternalFunctionAttributes - Set the attributes on the LLVM 670 /// function for the given decl and function info. This applies 671 /// attributes necessary for handling the ABI as well as user 672 /// specified attributes like section. 673 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, 674 const CGFunctionInfo &FI); 675 676 /// SetLLVMFunctionAttributes - Set the LLVM function attributes 677 /// (sext, zext, etc). 678 void SetLLVMFunctionAttributes(const Decl *D, 679 const CGFunctionInfo &Info, 680 llvm::Function *F); 681 682 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes 683 /// which only apply to a function definintion. 684 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F); 685 686 /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used 687 /// as a return type. 688 bool ReturnTypeUsesSRet(const CGFunctionInfo &FI); 689 690 /// ReturnTypeUsesSret - Return true iff the given type uses 'fpret' when used 691 /// as a return type. 692 bool ReturnTypeUsesFPRet(QualType ResultType); 693 694 /// ConstructAttributeList - Get the LLVM attributes and calling convention to 695 /// use for a particular function type. 696 /// 697 /// \param Info - The function type information. 698 /// \param TargetDecl - The decl these attributes are being constructed 699 /// for. If supplied the attributes applied to this decl may contribute to the 700 /// function attributes and calling convention. 701 /// \param PAL [out] - On return, the attribute list to use. 702 /// \param CallingConv [out] - On return, the LLVM calling convention to use. 703 void ConstructAttributeList(const CGFunctionInfo &Info, 704 const Decl *TargetDecl, 705 AttributeListType &PAL, 706 unsigned &CallingConv); 707 708 StringRef getMangledName(GlobalDecl GD); 709 void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 710 const BlockDecl *BD); 711 712 void EmitTentativeDefinition(const VarDecl *D); 713 714 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired); 715 716 llvm::GlobalVariable::LinkageTypes 717 getFunctionLinkage(const FunctionDecl *FD); 718 719 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) { 720 V->setLinkage(getFunctionLinkage(FD)); 721 } 722 723 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT, 724 /// and type information of the given class. 725 llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD); 726 727 /// GetTargetTypeStoreSize - Return the store size, in character units, of 728 /// the given LLVM type. 729 CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; 730 731 /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global 732 /// variable. 733 llvm::GlobalValue::LinkageTypes 734 GetLLVMLinkageVarDefinition(const VarDecl *D, 735 llvm::GlobalVariable *GV); 736 737 std::vector<const CXXRecordDecl*> DeferredVTables; 738 739 /// Emit all the global annotations. 740 void EmitGlobalAnnotations(); 741 742 /// Emit an annotation string. 743 llvm::Constant *EmitAnnotationString(llvm::StringRef Str); 744 745 /// Emit the annotation's translation unit. 746 llvm::Constant *EmitAnnotationUnit(SourceLocation Loc); 747 748 /// Emit the annotation line number. 749 llvm::Constant *EmitAnnotationLineNo(SourceLocation L); 750 751 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 752 /// annotation information for a given GlobalValue. The annotation struct is 753 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 754 /// GlobalValue being annotated. The second field is the constant string 755 /// created from the AnnotateAttr's annotation. The third field is a constant 756 /// string containing the name of the translation unit. The fourth field is 757 /// the line number in the file of the annotated value declaration. 758 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV, 759 const AnnotateAttr *AA, 760 SourceLocation L); 761 762 /// Add global annotations that are set on D, for the global GV. Those 763 /// annotations are emitted during finalization of the LLVM code. 764 void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV); 765 766 private: 767 llvm::GlobalValue *GetGlobalValue(StringRef Ref); 768 769 llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName, 770 llvm::Type *Ty, 771 GlobalDecl D, 772 bool ForVTable, 773 llvm::Attributes ExtraAttrs = 774 llvm::Attribute::None); 775 llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName, 776 llvm::PointerType *PTy, 777 const VarDecl *D, 778 bool UnnamedAddr = false); 779 780 /// SetCommonAttributes - Set attributes which are common to any 781 /// form of a global definition (alias, Objective-C method, 782 /// function, global variable). 783 /// 784 /// NOTE: This should only be called for definitions. 785 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV); 786 787 /// SetFunctionDefinitionAttributes - Set attributes for a global definition. 788 void SetFunctionDefinitionAttributes(const FunctionDecl *D, 789 llvm::GlobalValue *GV); 790 791 /// SetFunctionAttributes - Set function attributes for a function 792 /// declaration. 793 void SetFunctionAttributes(GlobalDecl GD, 794 llvm::Function *F, 795 bool IsIncompleteFunction); 796 797 /// EmitGlobal - Emit code for a singal global function or var decl. Forward 798 /// declarations are emitted lazily. 799 void EmitGlobal(GlobalDecl D); 800 801 void EmitGlobalDefinition(GlobalDecl D); 802 803 void EmitGlobalFunctionDefinition(GlobalDecl GD); 804 void EmitGlobalVarDefinition(const VarDecl *D); 805 void EmitAliasDefinition(GlobalDecl GD); 806 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); 807 void EmitObjCIvarInitializations(ObjCImplementationDecl *D); 808 809 // C++ related functions. 810 811 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target); 812 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D); 813 814 void EmitNamespace(const NamespaceDecl *D); 815 void EmitLinkageSpec(const LinkageSpecDecl *D); 816 817 /// EmitCXXConstructors - Emit constructors (base, complete) from a 818 /// C++ constructor Decl. 819 void EmitCXXConstructors(const CXXConstructorDecl *D); 820 821 /// EmitCXXConstructor - Emit a single constructor with the given type from 822 /// a C++ constructor Decl. 823 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type); 824 825 /// EmitCXXDestructors - Emit destructors (base, complete) from a 826 /// C++ destructor Decl. 827 void EmitCXXDestructors(const CXXDestructorDecl *D); 828 829 /// EmitCXXDestructor - Emit a single destructor with the given type from 830 /// a C++ destructor Decl. 831 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type); 832 833 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals. 834 void EmitCXXGlobalInitFunc(); 835 836 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals. 837 void EmitCXXGlobalDtorFunc(); 838 839 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 840 llvm::GlobalVariable *Addr); 841 842 // FIXME: Hardcoding priority here is gross. 843 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535); 844 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535); 845 846 /// EmitCtorList - Generates a global array of functions and priorities using 847 /// the given list and name. This array will have appending linkage and is 848 /// suitable for use as a LLVM constructor or destructor array. 849 void EmitCtorList(const CtorList &Fns, const char *GlobalName); 850 851 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the 852 /// given type. 853 void EmitFundamentalRTTIDescriptor(QualType Type); 854 855 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the 856 /// builtin types. 857 void EmitFundamentalRTTIDescriptors(); 858 859 /// EmitDeferred - Emit any needed decls for which code generation 860 /// was deferred. 861 void EmitDeferred(void); 862 863 /// EmitLLVMUsed - Emit the llvm.used metadata used to force 864 /// references to global which may otherwise be optimized out. 865 void EmitLLVMUsed(void); 866 867 void EmitDeclMetadata(); 868 869 /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where 870 /// to emit the .gcno and .gcda files in a way that persists in .bc files. 871 void EmitCoverageFile(); 872 873 /// MayDeferGeneration - Determine if the given decl can be emitted 874 /// lazily; this is only relevant for definitions. The given decl 875 /// must be either a function or var decl. 876 bool MayDeferGeneration(const ValueDecl *D); 877 878 /// SimplifyPersonality - Check whether we can use a "simpler", more 879 /// core exceptions personality function. 880 void SimplifyPersonality(); 881 }; 882 } // end namespace CodeGen 883 } // end namespace clang 884 885 #endif 886