CodeGenModule.cpp revision 194613
1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
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 coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CGDebugInfo.h"
16#include "CodeGenFunction.h"
17#include "CGCall.h"
18#include "CGObjCRuntime.h"
19#include "Mangle.h"
20#include "clang/Frontend/CompileOptions.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Basic/ConvertUTF.h"
29#include "llvm/CallingConv.h"
30#include "llvm/Module.h"
31#include "llvm/Intrinsics.h"
32#include "llvm/Target/TargetData.h"
33using namespace clang;
34using namespace CodeGen;
35
36
37CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
38                             llvm::Module &M, const llvm::TargetData &TD,
39                             Diagnostic &diags)
40  : BlockModule(C, M, TD, Types, *this), Context(C),
41    Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
42    TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
43    MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
44
45  if (!Features.ObjC1)
46    Runtime = 0;
47  else if (!Features.NeXTRuntime)
48    Runtime = CreateGNUObjCRuntime(*this);
49  else if (Features.ObjCNonFragileABI)
50    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
51  else
52    Runtime = CreateMacObjCRuntime(*this);
53
54  // If debug info generation is enabled, create the CGDebugInfo object.
55  DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
56}
57
58CodeGenModule::~CodeGenModule() {
59  delete Runtime;
60  delete DebugInfo;
61}
62
63void CodeGenModule::Release() {
64  EmitDeferred();
65  if (Runtime)
66    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
67      AddGlobalCtor(ObjCInitFunction);
68  EmitCtorList(GlobalCtors, "llvm.global_ctors");
69  EmitCtorList(GlobalDtors, "llvm.global_dtors");
70  EmitAnnotations();
71  EmitLLVMUsed();
72}
73
74/// ErrorUnsupported - Print out an error that codegen doesn't support the
75/// specified stmt yet.
76void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
77                                     bool OmitOnError) {
78  if (OmitOnError && getDiags().hasErrorOccurred())
79    return;
80  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
81                                               "cannot compile this %0 yet");
82  std::string Msg = Type;
83  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
84    << Msg << S->getSourceRange();
85}
86
87/// ErrorUnsupported - Print out an error that codegen doesn't support the
88/// specified decl yet.
89void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
90                                     bool OmitOnError) {
91  if (OmitOnError && getDiags().hasErrorOccurred())
92    return;
93  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
94                                               "cannot compile this %0 yet");
95  std::string Msg = Type;
96  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
97}
98
99LangOptions::VisibilityMode
100CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
101  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
102    if (VD->getStorageClass() == VarDecl::PrivateExtern)
103      return LangOptions::Hidden;
104
105  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>(getContext())) {
106    switch (attr->getVisibility()) {
107    default: assert(0 && "Unknown visibility!");
108    case VisibilityAttr::DefaultVisibility:
109      return LangOptions::Default;
110    case VisibilityAttr::HiddenVisibility:
111      return LangOptions::Hidden;
112    case VisibilityAttr::ProtectedVisibility:
113      return LangOptions::Protected;
114    }
115  }
116
117  return getLangOptions().getVisibilityMode();
118}
119
120void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
121                                        const Decl *D) const {
122  // Internal definitions always have default visibility.
123  if (GV->hasLocalLinkage()) {
124    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
125    return;
126  }
127
128  switch (getDeclVisibilityMode(D)) {
129  default: assert(0 && "Unknown visibility!");
130  case LangOptions::Default:
131    return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
132  case LangOptions::Hidden:
133    return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
134  case LangOptions::Protected:
135    return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
136  }
137}
138
139const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
140  const NamedDecl *ND = GD.getDecl();
141
142  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
143    return getMangledCXXCtorName(D, GD.getCtorType());
144  if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
145    return getMangledCXXDtorName(D, GD.getDtorType());
146
147  return getMangledName(ND);
148}
149
150/// \brief Retrieves the mangled name for the given declaration.
151///
152/// If the given declaration requires a mangled name, returns an
153/// const char* containing the mangled name.  Otherwise, returns
154/// the unmangled name.
155///
156const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
157  // In C, functions with no attributes never need to be mangled. Fastpath them.
158  if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
159    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
160    return ND->getNameAsCString();
161  }
162
163  llvm::SmallString<256> Name;
164  llvm::raw_svector_ostream Out(Name);
165  if (!mangleName(ND, Context, Out)) {
166    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
167    return ND->getNameAsCString();
168  }
169
170  Name += '\0';
171  return UniqueMangledName(Name.begin(), Name.end());
172}
173
174const char *CodeGenModule::UniqueMangledName(const char *NameStart,
175                                             const char *NameEnd) {
176  assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
177
178  return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
179}
180
181/// AddGlobalCtor - Add a function to the list that will be called before
182/// main() runs.
183void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
184  // FIXME: Type coercion of void()* types.
185  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
186}
187
188/// AddGlobalDtor - Add a function to the list that will be called
189/// when the module is unloaded.
190void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
191  // FIXME: Type coercion of void()* types.
192  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
193}
194
195void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
196  // Ctor function type is void()*.
197  llvm::FunctionType* CtorFTy =
198    llvm::FunctionType::get(llvm::Type::VoidTy,
199                            std::vector<const llvm::Type*>(),
200                            false);
201  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
202
203  // Get the type of a ctor entry, { i32, void ()* }.
204  llvm::StructType* CtorStructTy =
205    llvm::StructType::get(llvm::Type::Int32Ty,
206                          llvm::PointerType::getUnqual(CtorFTy), NULL);
207
208  // Construct the constructor and destructor arrays.
209  std::vector<llvm::Constant*> Ctors;
210  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
211    std::vector<llvm::Constant*> S;
212    S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
213    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
214    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
215  }
216
217  if (!Ctors.empty()) {
218    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
219    new llvm::GlobalVariable(AT, false,
220                             llvm::GlobalValue::AppendingLinkage,
221                             llvm::ConstantArray::get(AT, Ctors),
222                             GlobalName,
223                             &TheModule);
224  }
225}
226
227void CodeGenModule::EmitAnnotations() {
228  if (Annotations.empty())
229    return;
230
231  // Create a new global variable for the ConstantStruct in the Module.
232  llvm::Constant *Array =
233  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
234                                                Annotations.size()),
235                           Annotations);
236  llvm::GlobalValue *gv =
237  new llvm::GlobalVariable(Array->getType(), false,
238                           llvm::GlobalValue::AppendingLinkage, Array,
239                           "llvm.global.annotations", &TheModule);
240  gv->setSection("llvm.metadata");
241}
242
243static CodeGenModule::GVALinkage
244GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
245                      const LangOptions &Features) {
246  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
247    // C++ member functions defined inside the class are always inline.
248    if (MD->isInline() || !MD->isOutOfLine())
249      return CodeGenModule::GVA_CXXInline;
250
251    return CodeGenModule::GVA_StrongExternal;
252  }
253
254  // "static" functions get internal linkage.
255  if (FD->getStorageClass() == FunctionDecl::Static)
256    return CodeGenModule::GVA_Internal;
257
258  if (!FD->isInline())
259    return CodeGenModule::GVA_StrongExternal;
260
261  // If the inline function explicitly has the GNU inline attribute on it, or if
262  // this is C89 mode, we use to GNU semantics.
263  if (!Features.C99 && !Features.CPlusPlus) {
264    // extern inline in GNU mode is like C99 inline.
265    if (FD->getStorageClass() == FunctionDecl::Extern)
266      return CodeGenModule::GVA_C99Inline;
267    // Normal inline is a strong symbol.
268    return CodeGenModule::GVA_StrongExternal;
269  } else if (FD->hasActiveGNUInlineAttribute(Context)) {
270    // GCC in C99 mode seems to use a different decision-making
271    // process for extern inline, which factors in previous
272    // declarations.
273    if (FD->isExternGNUInline(Context))
274      return CodeGenModule::GVA_C99Inline;
275    // Normal inline is a strong symbol.
276    return CodeGenModule::GVA_StrongExternal;
277  }
278
279  // The definition of inline changes based on the language.  Note that we
280  // have already handled "static inline" above, with the GVA_Internal case.
281  if (Features.CPlusPlus)  // inline and extern inline.
282    return CodeGenModule::GVA_CXXInline;
283
284  assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode");
285  if (FD->isC99InlineDefinition())
286    return CodeGenModule::GVA_C99Inline;
287
288  return CodeGenModule::GVA_StrongExternal;
289}
290
291/// SetFunctionDefinitionAttributes - Set attributes for a global.
292///
293/// FIXME: This is currently only done for aliases and functions, but not for
294/// variables (these details are set in EmitGlobalVarDefinition for variables).
295void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
296                                                    llvm::GlobalValue *GV) {
297  GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
298
299  if (Linkage == GVA_Internal) {
300    GV->setLinkage(llvm::Function::InternalLinkage);
301  } else if (D->hasAttr<DLLExportAttr>(getContext())) {
302    GV->setLinkage(llvm::Function::DLLExportLinkage);
303  } else if (D->hasAttr<WeakAttr>(getContext())) {
304    GV->setLinkage(llvm::Function::WeakAnyLinkage);
305  } else if (Linkage == GVA_C99Inline) {
306    // In C99 mode, 'inline' functions are guaranteed to have a strong
307    // definition somewhere else, so we can use available_externally linkage.
308    GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
309  } else if (Linkage == GVA_CXXInline) {
310    // In C++, the compiler has to emit a definition in every translation unit
311    // that references the function.  We should use linkonce_odr because
312    // a) if all references in this translation unit are optimized away, we
313    // don't need to codegen it.  b) if the function persists, it needs to be
314    // merged with other definitions. c) C++ has the ODR, so we know the
315    // definition is dependable.
316    GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
317  } else {
318    assert(Linkage == GVA_StrongExternal);
319    // Otherwise, we have strong external linkage.
320    GV->setLinkage(llvm::Function::ExternalLinkage);
321  }
322
323  SetCommonAttributes(D, GV);
324}
325
326void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
327                                              const CGFunctionInfo &Info,
328                                              llvm::Function *F) {
329  AttributeListType AttributeList;
330  ConstructAttributeList(Info, D, AttributeList);
331
332  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
333                                        AttributeList.size()));
334
335  // Set the appropriate calling convention for the Function.
336  if (D->hasAttr<FastCallAttr>(getContext()))
337    F->setCallingConv(llvm::CallingConv::X86_FastCall);
338
339  if (D->hasAttr<StdCallAttr>(getContext()))
340    F->setCallingConv(llvm::CallingConv::X86_StdCall);
341}
342
343void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
344                                                           llvm::Function *F) {
345  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
346    F->addFnAttr(llvm::Attribute::NoUnwind);
347
348  if (D->hasAttr<AlwaysInlineAttr>(getContext()))
349    F->addFnAttr(llvm::Attribute::AlwaysInline);
350
351  if (D->hasAttr<NoinlineAttr>(getContext()))
352    F->addFnAttr(llvm::Attribute::NoInline);
353}
354
355void CodeGenModule::SetCommonAttributes(const Decl *D,
356                                        llvm::GlobalValue *GV) {
357  setGlobalVisibility(GV, D);
358
359  if (D->hasAttr<UsedAttr>(getContext()))
360    AddUsedGlobal(GV);
361
362  if (const SectionAttr *SA = D->getAttr<SectionAttr>(getContext()))
363    GV->setSection(SA->getName());
364}
365
366void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
367                                                  llvm::Function *F,
368                                                  const CGFunctionInfo &FI) {
369  SetLLVMFunctionAttributes(D, FI, F);
370  SetLLVMFunctionAttributesForDefinition(D, F);
371
372  F->setLinkage(llvm::Function::InternalLinkage);
373
374  SetCommonAttributes(D, F);
375}
376
377void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
378                                          llvm::Function *F,
379                                          bool IsIncompleteFunction) {
380  if (!IsIncompleteFunction)
381    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
382
383  // Only a few attributes are set on declarations; these may later be
384  // overridden by a definition.
385
386  if (FD->hasAttr<DLLImportAttr>(getContext())) {
387    F->setLinkage(llvm::Function::DLLImportLinkage);
388  } else if (FD->hasAttr<WeakAttr>(getContext()) ||
389             FD->hasAttr<WeakImportAttr>(getContext())) {
390    // "extern_weak" is overloaded in LLVM; we probably should have
391    // separate linkage types for this.
392    F->setLinkage(llvm::Function::ExternalWeakLinkage);
393  } else {
394    F->setLinkage(llvm::Function::ExternalLinkage);
395  }
396
397  if (const SectionAttr *SA = FD->getAttr<SectionAttr>(getContext()))
398    F->setSection(SA->getName());
399}
400
401void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
402  assert(!GV->isDeclaration() &&
403         "Only globals with definition can force usage.");
404  LLVMUsed.push_back(GV);
405}
406
407void CodeGenModule::EmitLLVMUsed() {
408  // Don't create llvm.used if there is no need.
409  if (LLVMUsed.empty())
410    return;
411
412  llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
413  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, LLVMUsed.size());
414
415  // Convert LLVMUsed to what ConstantArray needs.
416  std::vector<llvm::Constant*> UsedArray;
417  UsedArray.resize(LLVMUsed.size());
418  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
419    UsedArray[i] =
420     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
421  }
422
423  llvm::GlobalVariable *GV =
424    new llvm::GlobalVariable(ATy, false,
425                             llvm::GlobalValue::AppendingLinkage,
426                             llvm::ConstantArray::get(ATy, UsedArray),
427                             "llvm.used", &getModule());
428
429  GV->setSection("llvm.metadata");
430}
431
432void CodeGenModule::EmitDeferred() {
433  // Emit code for any potentially referenced deferred decls.  Since a
434  // previously unused static decl may become used during the generation of code
435  // for a static function, iterate until no  changes are made.
436  while (!DeferredDeclsToEmit.empty()) {
437    GlobalDecl D = DeferredDeclsToEmit.back();
438    DeferredDeclsToEmit.pop_back();
439
440    // The mangled name for the decl must have been emitted in GlobalDeclMap.
441    // Look it up to see if it was defined with a stronger definition (e.g. an
442    // extern inline function with a strong function redefinition).  If so,
443    // just ignore the deferred decl.
444    llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
445    assert(CGRef && "Deferred decl wasn't referenced?");
446
447    if (!CGRef->isDeclaration())
448      continue;
449
450    // Otherwise, emit the definition and move on to the next one.
451    EmitGlobalDefinition(D);
452  }
453}
454
455/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
456/// annotation information for a given GlobalValue.  The annotation struct is
457/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
458/// GlobalValue being annotated.  The second field is the constant string
459/// created from the AnnotateAttr's annotation.  The third field is a constant
460/// string containing the name of the translation unit.  The fourth field is
461/// the line number in the file of the annotated value declaration.
462///
463/// FIXME: this does not unique the annotation string constants, as llvm-gcc
464///        appears to.
465///
466llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
467                                                const AnnotateAttr *AA,
468                                                unsigned LineNo) {
469  llvm::Module *M = &getModule();
470
471  // get [N x i8] constants for the annotation string, and the filename string
472  // which are the 2nd and 3rd elements of the global annotation structure.
473  const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
474  llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
475  llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
476                                                  true);
477
478  // Get the two global values corresponding to the ConstantArrays we just
479  // created to hold the bytes of the strings.
480  const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
481  llvm::GlobalValue *annoGV =
482  new llvm::GlobalVariable(anno->getType(), false,
483                           llvm::GlobalValue::InternalLinkage, anno,
484                           GV->getName() + StringPrefix, M);
485  // translation unit name string, emitted into the llvm.metadata section.
486  llvm::GlobalValue *unitGV =
487  new llvm::GlobalVariable(unit->getType(), false,
488                           llvm::GlobalValue::InternalLinkage, unit,
489                           StringPrefix, M);
490
491  // Create the ConstantStruct for the global annotation.
492  llvm::Constant *Fields[4] = {
493    llvm::ConstantExpr::getBitCast(GV, SBP),
494    llvm::ConstantExpr::getBitCast(annoGV, SBP),
495    llvm::ConstantExpr::getBitCast(unitGV, SBP),
496    llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
497  };
498  return llvm::ConstantStruct::get(Fields, 4, false);
499}
500
501bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
502  // Never defer when EmitAllDecls is specified or the decl has
503  // attribute used.
504  if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>(getContext()))
505    return false;
506
507  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
508    // Constructors and destructors should never be deferred.
509    if (FD->hasAttr<ConstructorAttr>(getContext()) ||
510        FD->hasAttr<DestructorAttr>(getContext()))
511      return false;
512
513    GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
514
515    // static, static inline, always_inline, and extern inline functions can
516    // always be deferred.  Normal inline functions can be deferred in C99/C++.
517    if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
518        Linkage == GVA_CXXInline)
519      return true;
520    return false;
521  }
522
523  const VarDecl *VD = cast<VarDecl>(Global);
524  assert(VD->isFileVarDecl() && "Invalid decl");
525
526  return VD->getStorageClass() == VarDecl::Static;
527}
528
529void CodeGenModule::EmitGlobal(GlobalDecl GD) {
530  const ValueDecl *Global = GD.getDecl();
531
532  // If this is an alias definition (which otherwise looks like a declaration)
533  // emit it now.
534  if (Global->hasAttr<AliasAttr>(getContext()))
535    return EmitAliasDefinition(Global);
536
537  // Ignore declarations, they will be emitted on their first use.
538  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
539    // Forward declarations are emitted lazily on first use.
540    if (!FD->isThisDeclarationADefinition())
541      return;
542  } else {
543    const VarDecl *VD = cast<VarDecl>(Global);
544    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
545
546    // In C++, if this is marked "extern", defer code generation.
547    if (getLangOptions().CPlusPlus && !VD->getInit() &&
548        (VD->getStorageClass() == VarDecl::Extern ||
549         VD->isExternC(getContext())))
550      return;
551
552    // In C, if this isn't a definition, defer code generation.
553    if (!getLangOptions().CPlusPlus && !VD->getInit())
554      return;
555  }
556
557  // Defer code generation when possible if this is a static definition, inline
558  // function etc.  These we only want to emit if they are used.
559  if (MayDeferGeneration(Global)) {
560    // If the value has already been used, add it directly to the
561    // DeferredDeclsToEmit list.
562    const char *MangledName = getMangledName(GD);
563    if (GlobalDeclMap.count(MangledName))
564      DeferredDeclsToEmit.push_back(GD);
565    else {
566      // Otherwise, remember that we saw a deferred decl with this name.  The
567      // first use of the mangled name will cause it to move into
568      // DeferredDeclsToEmit.
569      DeferredDecls[MangledName] = GD;
570    }
571    return;
572  }
573
574  // Otherwise emit the definition.
575  EmitGlobalDefinition(GD);
576}
577
578void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
579  const ValueDecl *D = GD.getDecl();
580
581  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
582    EmitCXXConstructor(CD, GD.getCtorType());
583  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
584    EmitCXXDestructor(DD, GD.getDtorType());
585  else if (isa<FunctionDecl>(D))
586    EmitGlobalFunctionDefinition(GD);
587  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
588    EmitGlobalVarDefinition(VD);
589  else {
590    assert(0 && "Invalid argument to EmitGlobalDefinition()");
591  }
592}
593
594/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
595/// module, create and return an llvm Function with the specified type. If there
596/// is something in the module with the specified name, return it potentially
597/// bitcasted to the right type.
598///
599/// If D is non-null, it specifies a decl that correspond to this.  This is used
600/// to set the attributes on the function when it is first created.
601llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
602                                                       const llvm::Type *Ty,
603                                                       GlobalDecl D) {
604  // Lookup the entry, lazily creating it if necessary.
605  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
606  if (Entry) {
607    if (Entry->getType()->getElementType() == Ty)
608      return Entry;
609
610    // Make sure the result is of the correct type.
611    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
612    return llvm::ConstantExpr::getBitCast(Entry, PTy);
613  }
614
615  // This is the first use or definition of a mangled name.  If there is a
616  // deferred decl with this name, remember that we need to emit it at the end
617  // of the file.
618  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
619    DeferredDecls.find(MangledName);
620  if (DDI != DeferredDecls.end()) {
621    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
622    // list, and remove it from DeferredDecls (since we don't need it anymore).
623    DeferredDeclsToEmit.push_back(DDI->second);
624    DeferredDecls.erase(DDI);
625  } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
626    // If this the first reference to a C++ inline function in a class, queue up
627    // the deferred function body for emission.  These are not seen as
628    // top-level declarations.
629    if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
630      DeferredDeclsToEmit.push_back(D);
631  }
632
633  // This function doesn't have a complete type (for example, the return
634  // type is an incomplete struct). Use a fake type instead, and make
635  // sure not to try to set attributes.
636  bool IsIncompleteFunction = false;
637  if (!isa<llvm::FunctionType>(Ty)) {
638    Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
639                                 std::vector<const llvm::Type*>(), false);
640    IsIncompleteFunction = true;
641  }
642  llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
643                                             llvm::Function::ExternalLinkage,
644                                             "", &getModule());
645  F->setName(MangledName);
646  if (D.getDecl())
647    SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F,
648                          IsIncompleteFunction);
649  Entry = F;
650  return F;
651}
652
653/// GetAddrOfFunction - Return the address of the given function.  If Ty is
654/// non-null, then this function will use the specified type if it has to
655/// create it (this occurs when we see a definition of the function).
656llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
657                                                 const llvm::Type *Ty) {
658  // If there was no specific requested type, just convert it now.
659  if (!Ty)
660    Ty = getTypes().ConvertType(GD.getDecl()->getType());
661  return GetOrCreateLLVMFunction(getMangledName(GD.getDecl()), Ty, GD);
662}
663
664/// CreateRuntimeFunction - Create a new runtime function with the specified
665/// type and name.
666llvm::Constant *
667CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
668                                     const char *Name) {
669  // Convert Name to be a uniqued string from the IdentifierInfo table.
670  Name = getContext().Idents.get(Name).getName();
671  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
672}
673
674/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
675/// create and return an llvm GlobalVariable with the specified type.  If there
676/// is something in the module with the specified name, return it potentially
677/// bitcasted to the right type.
678///
679/// If D is non-null, it specifies a decl that correspond to this.  This is used
680/// to set the attributes on the global when it is first created.
681llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
682                                                     const llvm::PointerType*Ty,
683                                                     const VarDecl *D) {
684  // Lookup the entry, lazily creating it if necessary.
685  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
686  if (Entry) {
687    if (Entry->getType() == Ty)
688      return Entry;
689
690    // Make sure the result is of the correct type.
691    return llvm::ConstantExpr::getBitCast(Entry, Ty);
692  }
693
694  // This is the first use or definition of a mangled name.  If there is a
695  // deferred decl with this name, remember that we need to emit it at the end
696  // of the file.
697  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
698    DeferredDecls.find(MangledName);
699  if (DDI != DeferredDecls.end()) {
700    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
701    // list, and remove it from DeferredDecls (since we don't need it anymore).
702    DeferredDeclsToEmit.push_back(DDI->second);
703    DeferredDecls.erase(DDI);
704  }
705
706  llvm::GlobalVariable *GV =
707    new llvm::GlobalVariable(Ty->getElementType(), false,
708                             llvm::GlobalValue::ExternalLinkage,
709                             0, "", &getModule(),
710                             false, Ty->getAddressSpace());
711  GV->setName(MangledName);
712
713  // Handle things which are present even on external declarations.
714  if (D) {
715    // FIXME: This code is overly simple and should be merged with other global
716    // handling.
717    GV->setConstant(D->getType().isConstant(Context));
718
719    // FIXME: Merge with other attribute handling code.
720    if (D->getStorageClass() == VarDecl::PrivateExtern)
721      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
722
723    if (D->hasAttr<WeakAttr>(getContext()) ||
724        D->hasAttr<WeakImportAttr>(getContext()))
725      GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
726
727    GV->setThreadLocal(D->isThreadSpecified());
728  }
729
730  return Entry = GV;
731}
732
733
734/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
735/// given global variable.  If Ty is non-null and if the global doesn't exist,
736/// then it will be greated with the specified type instead of whatever the
737/// normal requested type would be.
738llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
739                                                  const llvm::Type *Ty) {
740  assert(D->hasGlobalStorage() && "Not a global variable");
741  QualType ASTTy = D->getType();
742  if (Ty == 0)
743    Ty = getTypes().ConvertTypeForMem(ASTTy);
744
745  const llvm::PointerType *PTy =
746    llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
747  return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
748}
749
750/// CreateRuntimeVariable - Create a new runtime global variable with the
751/// specified type and name.
752llvm::Constant *
753CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
754                                     const char *Name) {
755  // Convert Name to be a uniqued string from the IdentifierInfo table.
756  Name = getContext().Idents.get(Name).getName();
757  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
758}
759
760void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
761  assert(!D->getInit() && "Cannot emit definite definitions here!");
762
763  if (MayDeferGeneration(D)) {
764    // If we have not seen a reference to this variable yet, place it
765    // into the deferred declarations table to be emitted if needed
766    // later.
767    const char *MangledName = getMangledName(D);
768    if (GlobalDeclMap.count(MangledName) == 0) {
769      DeferredDecls[MangledName] = GlobalDecl(D);
770      return;
771    }
772  }
773
774  // The tentative definition is the only definition.
775  EmitGlobalVarDefinition(D);
776}
777
778void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
779  llvm::Constant *Init = 0;
780  QualType ASTTy = D->getType();
781
782  if (D->getInit() == 0) {
783    // This is a tentative definition; tentative definitions are
784    // implicitly initialized with { 0 }.
785    //
786    // Note that tentative definitions are only emitted at the end of
787    // a translation unit, so they should never have incomplete
788    // type. In addition, EmitTentativeDefinition makes sure that we
789    // never attempt to emit a tentative definition if a real one
790    // exists. A use may still exists, however, so we still may need
791    // to do a RAUW.
792    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
793    Init = llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(ASTTy));
794  } else {
795    Init = EmitConstantExpr(D->getInit(), D->getType());
796    if (!Init) {
797      ErrorUnsupported(D, "static initializer");
798      QualType T = D->getInit()->getType();
799      Init = llvm::UndefValue::get(getTypes().ConvertType(T));
800    }
801  }
802
803  const llvm::Type* InitType = Init->getType();
804  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
805
806  // Strip off a bitcast if we got one back.
807  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
808    assert(CE->getOpcode() == llvm::Instruction::BitCast);
809    Entry = CE->getOperand(0);
810  }
811
812  // Entry is now either a Function or GlobalVariable.
813  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
814
815  // We have a definition after a declaration with the wrong type.
816  // We must make a new GlobalVariable* and update everything that used OldGV
817  // (a declaration or tentative definition) with the new GlobalVariable*
818  // (which will be a definition).
819  //
820  // This happens if there is a prototype for a global (e.g.
821  // "extern int x[];") and then a definition of a different type (e.g.
822  // "int x[10];"). This also happens when an initializer has a different type
823  // from the type of the global (this happens with unions).
824  if (GV == 0 ||
825      GV->getType()->getElementType() != InitType ||
826      GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
827
828    // Remove the old entry from GlobalDeclMap so that we'll create a new one.
829    GlobalDeclMap.erase(getMangledName(D));
830
831    // Make a new global with the correct type, this is now guaranteed to work.
832    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
833    GV->takeName(cast<llvm::GlobalValue>(Entry));
834
835    // Replace all uses of the old global with the new global
836    llvm::Constant *NewPtrForOldDecl =
837        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
838    Entry->replaceAllUsesWith(NewPtrForOldDecl);
839
840    // Erase the old global, since it is no longer used.
841    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
842  }
843
844  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>(getContext())) {
845    SourceManager &SM = Context.getSourceManager();
846    AddAnnotation(EmitAnnotateAttr(GV, AA,
847                              SM.getInstantiationLineNumber(D->getLocation())));
848  }
849
850  GV->setInitializer(Init);
851  GV->setConstant(D->getType().isConstant(Context));
852  GV->setAlignment(getContext().getDeclAlignInBytes(D));
853
854  // Set the llvm linkage type as appropriate.
855  if (D->getStorageClass() == VarDecl::Static)
856    GV->setLinkage(llvm::Function::InternalLinkage);
857  else if (D->hasAttr<DLLImportAttr>(getContext()))
858    GV->setLinkage(llvm::Function::DLLImportLinkage);
859  else if (D->hasAttr<DLLExportAttr>(getContext()))
860    GV->setLinkage(llvm::Function::DLLExportLinkage);
861  else if (D->hasAttr<WeakAttr>(getContext()))
862    GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
863  else if (!CompileOpts.NoCommon &&
864           (!D->hasExternalStorage() && !D->getInit()))
865    GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
866  else
867    GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
868
869  SetCommonAttributes(D, GV);
870
871  // Emit global variable debug information.
872  if (CGDebugInfo *DI = getDebugInfo()) {
873    DI->setLocation(D->getLocation());
874    DI->EmitGlobalVariable(GV, D);
875  }
876}
877
878/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
879/// implement a function with no prototype, e.g. "int foo() {}".  If there are
880/// existing call uses of the old function in the module, this adjusts them to
881/// call the new function directly.
882///
883/// This is not just a cleanup: the always_inline pass requires direct calls to
884/// functions to be able to inline them.  If there is a bitcast in the way, it
885/// won't inline them.  Instcombine normally deletes these calls, but it isn't
886/// run at -O0.
887static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
888                                                      llvm::Function *NewFn) {
889  // If we're redefining a global as a function, don't transform it.
890  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
891  if (OldFn == 0) return;
892
893  const llvm::Type *NewRetTy = NewFn->getReturnType();
894  llvm::SmallVector<llvm::Value*, 4> ArgList;
895
896  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
897       UI != E; ) {
898    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
899    unsigned OpNo = UI.getOperandNo();
900    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
901    if (!CI || OpNo != 0) continue;
902
903    // If the return types don't match exactly, and if the call isn't dead, then
904    // we can't transform this call.
905    if (CI->getType() != NewRetTy && !CI->use_empty())
906      continue;
907
908    // If the function was passed too few arguments, don't transform.  If extra
909    // arguments were passed, we silently drop them.  If any of the types
910    // mismatch, we don't transform.
911    unsigned ArgNo = 0;
912    bool DontTransform = false;
913    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
914         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
915      if (CI->getNumOperands()-1 == ArgNo ||
916          CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
917        DontTransform = true;
918        break;
919      }
920    }
921    if (DontTransform)
922      continue;
923
924    // Okay, we can transform this.  Create the new call instruction and copy
925    // over the required information.
926    ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
927    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
928                                                     ArgList.end(), "", CI);
929    ArgList.clear();
930    if (NewCall->getType() != llvm::Type::VoidTy)
931      NewCall->takeName(CI);
932    NewCall->setCallingConv(CI->getCallingConv());
933    NewCall->setAttributes(CI->getAttributes());
934
935    // Finally, remove the old call, replacing any uses with the new one.
936    if (!CI->use_empty())
937      CI->replaceAllUsesWith(NewCall);
938    CI->eraseFromParent();
939  }
940}
941
942
943void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
944  const llvm::FunctionType *Ty;
945  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
946
947  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
948    bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
949
950    Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
951  } else {
952    Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
953
954    // As a special case, make sure that definitions of K&R function
955    // "type foo()" aren't declared as varargs (which forces the backend
956    // to do unnecessary work).
957    if (D->getType()->isFunctionNoProtoType()) {
958      assert(Ty->isVarArg() && "Didn't lower type as expected");
959      // Due to stret, the lowered function could have arguments.
960      // Just create the same type as was lowered by ConvertType
961      // but strip off the varargs bit.
962      std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
963      Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
964    }
965  }
966
967  // Get or create the prototype for the function.
968  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
969
970  // Strip off a bitcast if we got one back.
971  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
972    assert(CE->getOpcode() == llvm::Instruction::BitCast);
973    Entry = CE->getOperand(0);
974  }
975
976
977  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
978    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
979
980    // If the types mismatch then we have to rewrite the definition.
981    assert(OldFn->isDeclaration() &&
982           "Shouldn't replace non-declaration");
983
984    // F is the Function* for the one with the wrong type, we must make a new
985    // Function* and update everything that used F (a declaration) with the new
986    // Function* (which will be a definition).
987    //
988    // This happens if there is a prototype for a function
989    // (e.g. "int f()") and then a definition of a different type
990    // (e.g. "int f(int x)").  Start by making a new function of the
991    // correct type, RAUW, then steal the name.
992    GlobalDeclMap.erase(getMangledName(D));
993    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
994    NewFn->takeName(OldFn);
995
996    // If this is an implementation of a function without a prototype, try to
997    // replace any existing uses of the function (which may be calls) with uses
998    // of the new function
999    if (D->getType()->isFunctionNoProtoType()) {
1000      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1001      OldFn->removeDeadConstantUsers();
1002    }
1003
1004    // Replace uses of F with the Function we will endow with a body.
1005    if (!Entry->use_empty()) {
1006      llvm::Constant *NewPtrForOldDecl =
1007        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1008      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1009    }
1010
1011    // Ok, delete the old function now, which is dead.
1012    OldFn->eraseFromParent();
1013
1014    Entry = NewFn;
1015  }
1016
1017  llvm::Function *Fn = cast<llvm::Function>(Entry);
1018
1019  CodeGenFunction(*this).GenerateCode(D, Fn);
1020
1021  SetFunctionDefinitionAttributes(D, Fn);
1022  SetLLVMFunctionAttributesForDefinition(D, Fn);
1023
1024  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>(getContext()))
1025    AddGlobalCtor(Fn, CA->getPriority());
1026  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>(getContext()))
1027    AddGlobalDtor(Fn, DA->getPriority());
1028}
1029
1030void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
1031  const AliasAttr *AA = D->getAttr<AliasAttr>(getContext());
1032  assert(AA && "Not an alias?");
1033
1034  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1035
1036  // Unique the name through the identifier table.
1037  const char *AliaseeName = AA->getAliasee().c_str();
1038  AliaseeName = getContext().Idents.get(AliaseeName).getName();
1039
1040  // Create a reference to the named value.  This ensures that it is emitted
1041  // if a deferred decl.
1042  llvm::Constant *Aliasee;
1043  if (isa<llvm::FunctionType>(DeclTy))
1044    Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
1045  else
1046    Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1047                                    llvm::PointerType::getUnqual(DeclTy), 0);
1048
1049  // Create the new alias itself, but don't set a name yet.
1050  llvm::GlobalValue *GA =
1051    new llvm::GlobalAlias(Aliasee->getType(),
1052                          llvm::Function::ExternalLinkage,
1053                          "", Aliasee, &getModule());
1054
1055  // See if there is already something with the alias' name in the module.
1056  const char *MangledName = getMangledName(D);
1057  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1058
1059  if (Entry && !Entry->isDeclaration()) {
1060    // If there is a definition in the module, then it wins over the alias.
1061    // This is dubious, but allow it to be safe.  Just ignore the alias.
1062    GA->eraseFromParent();
1063    return;
1064  }
1065
1066  if (Entry) {
1067    // If there is a declaration in the module, then we had an extern followed
1068    // by the alias, as in:
1069    //   extern int test6();
1070    //   ...
1071    //   int test6() __attribute__((alias("test7")));
1072    //
1073    // Remove it and replace uses of it with the alias.
1074
1075    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1076                                                          Entry->getType()));
1077    Entry->eraseFromParent();
1078  }
1079
1080  // Now we know that there is no conflict, set the name.
1081  Entry = GA;
1082  GA->setName(MangledName);
1083
1084  // Set attributes which are particular to an alias; this is a
1085  // specialization of the attributes which may be set on a global
1086  // variable/function.
1087  if (D->hasAttr<DLLExportAttr>(getContext())) {
1088    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1089      // The dllexport attribute is ignored for undefined symbols.
1090      if (FD->getBody(getContext()))
1091        GA->setLinkage(llvm::Function::DLLExportLinkage);
1092    } else {
1093      GA->setLinkage(llvm::Function::DLLExportLinkage);
1094    }
1095  } else if (D->hasAttr<WeakAttr>(getContext()) ||
1096             D->hasAttr<WeakImportAttr>(getContext())) {
1097    GA->setLinkage(llvm::Function::WeakAnyLinkage);
1098  }
1099
1100  SetCommonAttributes(D, GA);
1101}
1102
1103/// getBuiltinLibFunction - Given a builtin id for a function like
1104/// "__builtin_fabsf", return a Function* for "fabsf".
1105llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
1106  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1107          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1108         "isn't a lib fn");
1109
1110  // Get the name, skip over the __builtin_ prefix (if necessary).
1111  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1112  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1113    Name += 10;
1114
1115  // Get the type for the builtin.
1116  ASTContext::GetBuiltinTypeError Error;
1117  QualType Type = Context.GetBuiltinType(BuiltinID, Error);
1118  assert(Error == ASTContext::GE_None && "Can't get builtin type");
1119
1120  const llvm::FunctionType *Ty =
1121    cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1122
1123  // Unique the name through the identifier table.
1124  Name = getContext().Idents.get(Name).getName();
1125  // FIXME: param attributes for sext/zext etc.
1126  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1127}
1128
1129llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1130                                            unsigned NumTys) {
1131  return llvm::Intrinsic::getDeclaration(&getModule(),
1132                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
1133}
1134
1135llvm::Function *CodeGenModule::getMemCpyFn() {
1136  if (MemCpyFn) return MemCpyFn;
1137  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1138  return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
1139}
1140
1141llvm::Function *CodeGenModule::getMemMoveFn() {
1142  if (MemMoveFn) return MemMoveFn;
1143  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1144  return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
1145}
1146
1147llvm::Function *CodeGenModule::getMemSetFn() {
1148  if (MemSetFn) return MemSetFn;
1149  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1150  return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
1151}
1152
1153static void appendFieldAndPadding(CodeGenModule &CGM,
1154                                  std::vector<llvm::Constant*>& Fields,
1155                                  FieldDecl *FieldD, FieldDecl *NextFieldD,
1156                                  llvm::Constant* Field,
1157                                  RecordDecl* RD, const llvm::StructType *STy) {
1158  // Append the field.
1159  Fields.push_back(Field);
1160
1161  int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
1162
1163  int NextStructFieldNo;
1164  if (!NextFieldD) {
1165    NextStructFieldNo = STy->getNumElements();
1166  } else {
1167    NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
1168  }
1169
1170  // Append padding
1171  for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1172    llvm::Constant *C =
1173      llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1174
1175    Fields.push_back(C);
1176  }
1177}
1178
1179llvm::Constant *CodeGenModule::
1180GetAddrOfConstantCFString(const StringLiteral *Literal) {
1181  std::string str;
1182  unsigned StringLength = 0;
1183
1184  bool isUTF16 = false;
1185  if (Literal->containsNonAsciiOrNull()) {
1186    // Convert from UTF-8 to UTF-16.
1187    llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1188    const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1189    UTF16 *ToPtr = &ToBuf[0];
1190
1191    ConversionResult Result;
1192    Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1193                                &ToPtr, ToPtr+Literal->getByteLength(),
1194                                strictConversion);
1195    if (Result == conversionOK) {
1196      // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1197      // without doing more surgery to this routine. Since we aren't explicitly
1198      // checking for endianness here, it's also a bug (when generating code for
1199      // a target that doesn't match the host endianness). Modeling this as an
1200      // i16 array is likely the cleanest solution.
1201      StringLength = ToPtr-&ToBuf[0];
1202      str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1203      isUTF16 = true;
1204    } else if (Result == sourceIllegal) {
1205      // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
1206      str.assign(Literal->getStrData(), Literal->getByteLength());
1207      StringLength = str.length();
1208    } else
1209      assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
1210
1211  } else {
1212    str.assign(Literal->getStrData(), Literal->getByteLength());
1213    StringLength = str.length();
1214  }
1215  llvm::StringMapEntry<llvm::Constant *> &Entry =
1216    CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1217
1218  if (llvm::Constant *C = Entry.getValue())
1219    return C;
1220
1221  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1222  llvm::Constant *Zeros[] = { Zero, Zero };
1223
1224  if (!CFConstantStringClassRef) {
1225    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1226    Ty = llvm::ArrayType::get(Ty, 0);
1227
1228    // FIXME: This is fairly broken if __CFConstantStringClassReference is
1229    // already defined, in that it will get renamed and the user will most
1230    // likely see an opaque error message. This is a general issue with relying
1231    // on particular names.
1232    llvm::GlobalVariable *GV =
1233      new llvm::GlobalVariable(Ty, false,
1234                               llvm::GlobalVariable::ExternalLinkage, 0,
1235                               "__CFConstantStringClassReference",
1236                               &getModule());
1237
1238    // Decay array -> ptr
1239    CFConstantStringClassRef =
1240      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1241  }
1242
1243  QualType CFTy = getContext().getCFConstantStringType();
1244  RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
1245
1246  const llvm::StructType *STy =
1247    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1248
1249  std::vector<llvm::Constant*> Fields;
1250  RecordDecl::field_iterator Field = CFRD->field_begin(getContext());
1251
1252  // Class pointer.
1253  FieldDecl *CurField = *Field++;
1254  FieldDecl *NextField = *Field++;
1255  appendFieldAndPadding(*this, Fields, CurField, NextField,
1256                        CFConstantStringClassRef, CFRD, STy);
1257
1258  // Flags.
1259  CurField = NextField;
1260  NextField = *Field++;
1261  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1262  appendFieldAndPadding(*this, Fields, CurField, NextField,
1263                        isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1264                                : llvm::ConstantInt::get(Ty, 0x07C8),
1265                        CFRD, STy);
1266
1267  // String pointer.
1268  CurField = NextField;
1269  NextField = *Field++;
1270  llvm::Constant *C = llvm::ConstantArray::get(str);
1271
1272  const char *Sect, *Prefix;
1273  bool isConstant;
1274  if (isUTF16) {
1275    Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1276    Sect = getContext().Target.getUnicodeStringSection();
1277    // FIXME: Why does GCC not set constant here?
1278    isConstant = false;
1279  } else {
1280    Prefix = getContext().Target.getStringSymbolPrefix(true);
1281    Sect = getContext().Target.getCFStringDataSection();
1282    // FIXME: -fwritable-strings should probably affect this, but we
1283    // are following gcc here.
1284    isConstant = true;
1285  }
1286  llvm::GlobalVariable *GV =
1287    new llvm::GlobalVariable(C->getType(), isConstant,
1288                             llvm::GlobalValue::InternalLinkage,
1289                             C, Prefix, &getModule());
1290  if (Sect)
1291    GV->setSection(Sect);
1292  if (isUTF16) {
1293    unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1294    GV->setAlignment(Align);
1295  }
1296  appendFieldAndPadding(*this, Fields, CurField, NextField,
1297                        llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
1298                        CFRD, STy);
1299
1300  // String length.
1301  CurField = NextField;
1302  NextField = 0;
1303  Ty = getTypes().ConvertType(getContext().LongTy);
1304  appendFieldAndPadding(*this, Fields, CurField, NextField,
1305                        llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
1306
1307  // The struct.
1308  C = llvm::ConstantStruct::get(STy, Fields);
1309  GV = new llvm::GlobalVariable(C->getType(), true,
1310                                llvm::GlobalVariable::InternalLinkage, C,
1311                                getContext().Target.getCFStringSymbolPrefix(),
1312                                &getModule());
1313  if (const char *Sect = getContext().Target.getCFStringSection())
1314    GV->setSection(Sect);
1315  Entry.setValue(GV);
1316
1317  return GV;
1318}
1319
1320/// GetStringForStringLiteral - Return the appropriate bytes for a
1321/// string literal, properly padded to match the literal type.
1322std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1323  const char *StrData = E->getStrData();
1324  unsigned Len = E->getByteLength();
1325
1326  const ConstantArrayType *CAT =
1327    getContext().getAsConstantArrayType(E->getType());
1328  assert(CAT && "String isn't pointer or array!");
1329
1330  // Resize the string to the right size.
1331  std::string Str(StrData, StrData+Len);
1332  uint64_t RealLen = CAT->getSize().getZExtValue();
1333
1334  if (E->isWide())
1335    RealLen *= getContext().Target.getWCharWidth()/8;
1336
1337  Str.resize(RealLen, '\0');
1338
1339  return Str;
1340}
1341
1342/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1343/// constant array for the given string literal.
1344llvm::Constant *
1345CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1346  // FIXME: This can be more efficient.
1347  return GetAddrOfConstantString(GetStringForStringLiteral(S));
1348}
1349
1350/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1351/// array for the given ObjCEncodeExpr node.
1352llvm::Constant *
1353CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1354  std::string Str;
1355  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1356
1357  return GetAddrOfConstantCString(Str);
1358}
1359
1360
1361/// GenerateWritableString -- Creates storage for a string literal.
1362static llvm::Constant *GenerateStringLiteral(const std::string &str,
1363                                             bool constant,
1364                                             CodeGenModule &CGM,
1365                                             const char *GlobalName) {
1366  // Create Constant for this string literal. Don't add a '\0'.
1367  llvm::Constant *C = llvm::ConstantArray::get(str, false);
1368
1369  // Create a global variable for this string
1370  return new llvm::GlobalVariable(C->getType(), constant,
1371                                  llvm::GlobalValue::InternalLinkage,
1372                                  C, GlobalName, &CGM.getModule());
1373}
1374
1375/// GetAddrOfConstantString - Returns a pointer to a character array
1376/// containing the literal. This contents are exactly that of the
1377/// given string, i.e. it will not be null terminated automatically;
1378/// see GetAddrOfConstantCString. Note that whether the result is
1379/// actually a pointer to an LLVM constant depends on
1380/// Feature.WriteableStrings.
1381///
1382/// The result has pointer to array type.
1383llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1384                                                       const char *GlobalName) {
1385  bool IsConstant = !Features.WritableStrings;
1386
1387  // Get the default prefix if a name wasn't specified.
1388  if (!GlobalName)
1389    GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1390
1391  // Don't share any string literals if strings aren't constant.
1392  if (!IsConstant)
1393    return GenerateStringLiteral(str, false, *this, GlobalName);
1394
1395  llvm::StringMapEntry<llvm::Constant *> &Entry =
1396  ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1397
1398  if (Entry.getValue())
1399    return Entry.getValue();
1400
1401  // Create a global variable for this.
1402  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1403  Entry.setValue(C);
1404  return C;
1405}
1406
1407/// GetAddrOfConstantCString - Returns a pointer to a character
1408/// array containing the literal and a terminating '\-'
1409/// character. The result has pointer to array type.
1410llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1411                                                        const char *GlobalName){
1412  return GetAddrOfConstantString(str + '\0', GlobalName);
1413}
1414
1415/// EmitObjCPropertyImplementations - Emit information for synthesized
1416/// properties for an implementation.
1417void CodeGenModule::EmitObjCPropertyImplementations(const
1418                                                    ObjCImplementationDecl *D) {
1419  for (ObjCImplementationDecl::propimpl_iterator
1420         i = D->propimpl_begin(getContext()),
1421         e = D->propimpl_end(getContext()); i != e; ++i) {
1422    ObjCPropertyImplDecl *PID = *i;
1423
1424    // Dynamic is just for type-checking.
1425    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1426      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1427
1428      // Determine which methods need to be implemented, some may have
1429      // been overridden. Note that ::isSynthesized is not the method
1430      // we want, that just indicates if the decl came from a
1431      // property. What we want to know is if the method is defined in
1432      // this implementation.
1433      if (!D->getInstanceMethod(getContext(), PD->getGetterName()))
1434        CodeGenFunction(*this).GenerateObjCGetter(
1435                                 const_cast<ObjCImplementationDecl *>(D), PID);
1436      if (!PD->isReadOnly() &&
1437          !D->getInstanceMethod(getContext(), PD->getSetterName()))
1438        CodeGenFunction(*this).GenerateObjCSetter(
1439                                 const_cast<ObjCImplementationDecl *>(D), PID);
1440    }
1441  }
1442}
1443
1444/// EmitNamespace - Emit all declarations in a namespace.
1445void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1446  for (RecordDecl::decl_iterator I = ND->decls_begin(getContext()),
1447         E = ND->decls_end(getContext());
1448       I != E; ++I)
1449    EmitTopLevelDecl(*I);
1450}
1451
1452// EmitLinkageSpec - Emit all declarations in a linkage spec.
1453void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1454  if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1455    ErrorUnsupported(LSD, "linkage spec");
1456    return;
1457  }
1458
1459  for (RecordDecl::decl_iterator I = LSD->decls_begin(getContext()),
1460         E = LSD->decls_end(getContext());
1461       I != E; ++I)
1462    EmitTopLevelDecl(*I);
1463}
1464
1465/// EmitTopLevelDecl - Emit code for a single top level declaration.
1466void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1467  // If an error has occurred, stop code generation, but continue
1468  // parsing and semantic analysis (to ensure all warnings and errors
1469  // are emitted).
1470  if (Diags.hasErrorOccurred())
1471    return;
1472
1473  switch (D->getKind()) {
1474  case Decl::CXXMethod:
1475  case Decl::Function:
1476  case Decl::Var:
1477    EmitGlobal(GlobalDecl(cast<ValueDecl>(D)));
1478    break;
1479
1480  // C++ Decls
1481  case Decl::Namespace:
1482    EmitNamespace(cast<NamespaceDecl>(D));
1483    break;
1484    // No code generation needed.
1485  case Decl::Using:
1486    break;
1487  case Decl::CXXConstructor:
1488    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1489    break;
1490  case Decl::CXXDestructor:
1491    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1492    break;
1493
1494  case Decl::StaticAssert:
1495    // Nothing to do.
1496    break;
1497
1498  // Objective-C Decls
1499
1500  // Forward declarations, no (immediate) code generation.
1501  case Decl::ObjCClass:
1502  case Decl::ObjCForwardProtocol:
1503  case Decl::ObjCCategory:
1504  case Decl::ObjCInterface:
1505    break;
1506
1507  case Decl::ObjCProtocol:
1508    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1509    break;
1510
1511  case Decl::ObjCCategoryImpl:
1512    // Categories have properties but don't support synthesize so we
1513    // can ignore them here.
1514    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1515    break;
1516
1517  case Decl::ObjCImplementation: {
1518    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1519    EmitObjCPropertyImplementations(OMD);
1520    Runtime->GenerateClass(OMD);
1521    break;
1522  }
1523  case Decl::ObjCMethod: {
1524    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1525    // If this is not a prototype, emit the body.
1526    if (OMD->getBody(getContext()))
1527      CodeGenFunction(*this).GenerateObjCMethod(OMD);
1528    break;
1529  }
1530  case Decl::ObjCCompatibleAlias:
1531    // compatibility-alias is a directive and has no code gen.
1532    break;
1533
1534  case Decl::LinkageSpec:
1535    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1536    break;
1537
1538  case Decl::FileScopeAsm: {
1539    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1540    std::string AsmString(AD->getAsmString()->getStrData(),
1541                          AD->getAsmString()->getByteLength());
1542
1543    const std::string &S = getModule().getModuleInlineAsm();
1544    if (S.empty())
1545      getModule().setModuleInlineAsm(AsmString);
1546    else
1547      getModule().setModuleInlineAsm(S + '\n' + AsmString);
1548    break;
1549  }
1550
1551  default:
1552    // Make sure we handled everything we should, every other kind is a
1553    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1554    // function. Need to recode Decl::Kind to do that easily.
1555    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1556  }
1557}
1558