CodeGenModule.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. #include "CodeGenModule.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/Basic/Diagnostic.h"
  18. #include "clang/Basic/LangOptions.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "llvm/CallingConv.h"
  21. #include "llvm/Constants.h"
  22. #include "llvm/DerivedTypes.h"
  23. #include "llvm/Module.h"
  24. #include "llvm/Intrinsics.h"
  25. #include <algorithm>
  26. using namespace clang;
  27. using namespace CodeGen;
  28. CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
  29. llvm::Module &M, const llvm::TargetData &TD,
  30. Diagnostic &diags)
  31. : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
  32. Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
  33. //TODO: Make this selectable at runtime
  34. Runtime = CreateObjCRuntime(M,
  35. getTypes().ConvertType(getContext().IntTy),
  36. getTypes().ConvertType(getContext().LongTy));
  37. }
  38. CodeGenModule::~CodeGenModule() {
  39. llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
  40. if (ObjCInitFunction) {
  41. AddGlobalCtor(ObjCInitFunction);
  42. }
  43. EmitGlobalCtors();
  44. delete Runtime;
  45. }
  46. /// WarnUnsupported - Print out a warning that codegen doesn't support the
  47. /// specified stmt yet.
  48. void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
  49. unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
  50. "cannot codegen this %0 yet");
  51. SourceRange Range = S->getSourceRange();
  52. std::string Msg = Type;
  53. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
  54. &Msg, 1, &Range, 1);
  55. }
  56. /// WarnUnsupported - Print out a warning that codegen doesn't support the
  57. /// specified decl yet.
  58. void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
  59. unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
  60. "cannot codegen this %0 yet");
  61. std::string Msg = Type;
  62. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
  63. &Msg, 1);
  64. }
  65. /// AddGlobalCtor - Add a function to the list that will be called before
  66. /// main() runs.
  67. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
  68. // TODO: Type coercion of void()* types.
  69. GlobalCtors.push_back(Ctor);
  70. }
  71. /// EmitGlobalCtors - Generates the array of contsturctor functions to be
  72. /// called on module load, if any have been registered with AddGlobalCtor.
  73. void CodeGenModule::EmitGlobalCtors() {
  74. if (GlobalCtors.empty()) return;
  75. // Get the type of @llvm.global_ctors
  76. std::vector<const llvm::Type*> CtorFields;
  77. CtorFields.push_back(llvm::IntegerType::get(32));
  78. // Constructor function type
  79. std::vector<const llvm::Type*> VoidArgs;
  80. llvm::FunctionType* CtorFuncTy = llvm::FunctionType::get(
  81. llvm::Type::VoidTy,
  82. VoidArgs,
  83. false);
  84. // i32, function type pair
  85. const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
  86. llvm::StructType* CtorStructTy =
  87. llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
  88. // Array of fields
  89. llvm::ArrayType* GlobalCtorsTy =
  90. llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
  91. // Define the global variable
  92. llvm::GlobalVariable *GlobalCtorsVal =
  93. new llvm::GlobalVariable(GlobalCtorsTy, false,
  94. llvm::GlobalValue::AppendingLinkage,
  95. (llvm::Constant*)0, "llvm.global_ctors",
  96. &TheModule);
  97. // Populate the array
  98. std::vector<llvm::Constant*> CtorValues;
  99. llvm::Constant *MagicNumber =
  100. llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
  101. std::vector<llvm::Constant*> StructValues;
  102. for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
  103. E = GlobalCtors.end(); I != E; ++I) {
  104. StructValues.clear();
  105. StructValues.push_back(MagicNumber);
  106. StructValues.push_back(*I);
  107. CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
  108. }
  109. GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
  110. CtorValues));
  111. }
  112. /// ReplaceMapValuesWith - This is a really slow and bad function that
  113. /// searches for any entries in GlobalDeclMap that point to OldVal, changing
  114. /// them to point to NewVal. This is badbadbad, FIXME!
  115. void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
  116. llvm::Constant *NewVal) {
  117. for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
  118. I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
  119. if (I->second == OldVal) I->second = NewVal;
  120. }
  121. llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
  122. bool isDefinition) {
  123. // See if it is already in the map. If so, just return it.
  124. llvm::Constant *&Entry = GlobalDeclMap[D];
  125. if (Entry) return Entry;
  126. const llvm::Type *Ty = getTypes().ConvertType(D->getType());
  127. // Check to see if the function already exists.
  128. llvm::Function *F = getModule().getFunction(D->getName());
  129. const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
  130. // If it doesn't already exist, just create and return an entry.
  131. if (F == 0) {
  132. // FIXME: param attributes for sext/zext etc.
  133. F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(),
  134. &getModule());
  135. // Set the appropriate calling convention for the Function.
  136. if (D->getAttr<FastCallAttr>())
  137. F->setCallingConv(llvm::CallingConv::Fast);
  138. return Entry = F;
  139. }
  140. // If the pointer type matches, just return it.
  141. llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
  142. if (PFTy == F->getType()) return Entry = F;
  143. // If this isn't a definition, just return it casted to the right type.
  144. if (!isDefinition)
  145. return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
  146. // Otherwise, we have a definition after a prototype with the wrong type.
  147. // F is the Function* for the one with the wrong type, we must make a new
  148. // Function* and update everything that used F (a declaration) with the new
  149. // Function* (which will be a definition).
  150. //
  151. // This happens if there is a prototype for a function (e.g. "int f()") and
  152. // then a definition of a different type (e.g. "int f(int x)"). Start by
  153. // making a new function of the correct type, RAUW, then steal the name.
  154. llvm::Function *NewFn = new llvm::Function(FTy,
  155. llvm::Function::ExternalLinkage,
  156. "", &getModule());
  157. NewFn->takeName(F);
  158. // Replace uses of F with the Function we will endow with a body.
  159. llvm::Constant *NewPtrForOldDecl =
  160. llvm::ConstantExpr::getBitCast(NewFn, F->getType());
  161. F->replaceAllUsesWith(NewPtrForOldDecl);
  162. // FIXME: Update the globaldeclmap for the previous decl of this name. We
  163. // really want a way to walk all of these, but we don't have it yet. This
  164. // is incredibly slow!
  165. ReplaceMapValuesWith(F, NewPtrForOldDecl);
  166. // Ok, delete the old function now, which is dead.
  167. assert(F->isDeclaration() && "Shouldn't replace non-declaration");
  168. F->eraseFromParent();
  169. // Return the new function which has the right type.
  170. return Entry = NewFn;
  171. }
  172. static bool IsZeroElementArray(const llvm::Type *Ty) {
  173. if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
  174. return ATy->getNumElements() == 0;
  175. return false;
  176. }
  177. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  178. bool isDefinition) {
  179. assert(D->hasGlobalStorage() && "Not a global variable");
  180. // See if it is already in the map.
  181. llvm::Constant *&Entry = GlobalDeclMap[D];
  182. if (Entry) return Entry;
  183. QualType ASTTy = D->getType();
  184. const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
  185. // Check to see if the global already exists.
  186. llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
  187. // If it doesn't already exist, just create and return an entry.
  188. if (GV == 0) {
  189. return Entry = new llvm::GlobalVariable(Ty, false,
  190. llvm::GlobalValue::ExternalLinkage,
  191. 0, D->getName(), &getModule(), 0,
  192. ASTTy.getAddressSpace());
  193. }
  194. // If the pointer type matches, just return it.
  195. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  196. if (PTy == GV->getType()) return Entry = GV;
  197. // If this isn't a definition, just return it casted to the right type.
  198. if (!isDefinition)
  199. return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
  200. // Otherwise, we have a definition after a prototype with the wrong type.
  201. // GV is the GlobalVariable* for the one with the wrong type, we must make a
  202. /// new GlobalVariable* and update everything that used GV (a declaration)
  203. // with the new GlobalVariable* (which will be a definition).
  204. //
  205. // This happens if there is a prototype for a global (e.g. "extern int x[];")
  206. // and then a definition of a different type (e.g. "int x[10];"). Start by
  207. // making a new global of the correct type, RAUW, then steal the name.
  208. llvm::GlobalVariable *NewGV =
  209. new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
  210. 0, D->getName(), &getModule(), 0,
  211. ASTTy.getAddressSpace());
  212. NewGV->takeName(GV);
  213. // Replace uses of GV with the globalvalue we will endow with a body.
  214. llvm::Constant *NewPtrForOldDecl =
  215. llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
  216. GV->replaceAllUsesWith(NewPtrForOldDecl);
  217. // FIXME: Update the globaldeclmap for the previous decl of this name. We
  218. // really want a way to walk all of these, but we don't have it yet. This
  219. // is incredibly slow!
  220. ReplaceMapValuesWith(GV, NewPtrForOldDecl);
  221. // Verify that GV was a declaration or something like x[] which turns into
  222. // [0 x type].
  223. assert((GV->isDeclaration() ||
  224. IsZeroElementArray(GV->getType()->getElementType())) &&
  225. "Shouldn't replace non-declaration");
  226. // Ok, delete the old global now, which is dead.
  227. GV->eraseFromParent();
  228. // Return the new global which has the right type.
  229. return Entry = NewGV;
  230. }
  231. void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
  232. // If this is not a prototype, emit the body.
  233. if (OMD->getBody())
  234. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  235. }
  236. void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
  237. // If this is not a prototype, emit the body.
  238. if (FD->getBody())
  239. CodeGenFunction(*this).GenerateCode(FD);
  240. }
  241. llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
  242. return EmitConstantExpr(Expr);
  243. }
  244. void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
  245. // If this is just a forward declaration of the variable, don't emit it now,
  246. // allow it to be emitted lazily on its first use.
  247. if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
  248. return;
  249. // Get the global, forcing it to be a direct reference.
  250. llvm::GlobalVariable *GV =
  251. cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
  252. // Convert the initializer, or use zero if appropriate.
  253. llvm::Constant *Init = 0;
  254. if (D->getInit() == 0) {
  255. Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
  256. } else if (D->getType()->isIntegerType()) {
  257. llvm::APSInt Value(static_cast<uint32_t>(
  258. getContext().getTypeSize(D->getInit()->getType())));
  259. if (D->getInit()->isIntegerConstantExpr(Value, Context))
  260. Init = llvm::ConstantInt::get(Value);
  261. }
  262. if (!Init)
  263. Init = EmitGlobalInit(D->getInit());
  264. assert(GV->getType()->getElementType() == Init->getType() &&
  265. "Initializer codegen type mismatch!");
  266. GV->setInitializer(Init);
  267. if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
  268. GV->setVisibility(attr->getVisibility());
  269. // FIXME: else handle -fvisibility
  270. // Set the llvm linkage type as appropriate.
  271. if (D->getAttr<DLLImportAttr>())
  272. GV->setLinkage(llvm::Function::DLLImportLinkage);
  273. else if (D->getAttr<DLLExportAttr>())
  274. GV->setLinkage(llvm::Function::DLLExportLinkage);
  275. else if (D->getAttr<WeakAttr>()) {
  276. GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
  277. } else {
  278. // FIXME: This isn't right. This should handle common linkage and other
  279. // stuff.
  280. switch (D->getStorageClass()) {
  281. case VarDecl::Auto:
  282. case VarDecl::Register:
  283. assert(0 && "Can't have auto or register globals");
  284. case VarDecl::None:
  285. if (!D->getInit())
  286. GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
  287. break;
  288. case VarDecl::Extern:
  289. case VarDecl::PrivateExtern:
  290. // todo: common
  291. break;
  292. case VarDecl::Static:
  293. GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
  294. break;
  295. }
  296. }
  297. }
  298. /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
  299. /// declarator chain.
  300. void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
  301. for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
  302. EmitGlobalVar(D);
  303. }
  304. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  305. // Make sure that this type is translated.
  306. Types.UpdateCompletedType(TD);
  307. }
  308. /// getBuiltinLibFunction
  309. llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
  310. if (BuiltinID > BuiltinFunctions.size())
  311. BuiltinFunctions.resize(BuiltinID);
  312. // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
  313. // a slot for it.
  314. assert(BuiltinID && "Invalid Builtin ID");
  315. llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
  316. if (FunctionSlot)
  317. return FunctionSlot;
  318. assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
  319. // Get the name, skip over the __builtin_ prefix.
  320. const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
  321. // Get the type for the builtin.
  322. QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
  323. const llvm::FunctionType *Ty =
  324. cast<llvm::FunctionType>(getTypes().ConvertType(Type));
  325. // FIXME: This has a serious problem with code like this:
  326. // void abs() {}
  327. // ... __builtin_abs(x);
  328. // The two versions of abs will collide. The fix is for the builtin to win,
  329. // and for the existing one to be turned into a constantexpr cast of the
  330. // builtin. In the case where the existing one is a static function, it
  331. // should just be renamed.
  332. if (llvm::Function *Existing = getModule().getFunction(Name)) {
  333. if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
  334. return FunctionSlot = Existing;
  335. assert(Existing == 0 && "FIXME: Name collision");
  336. }
  337. // FIXME: param attributes for sext/zext etc.
  338. return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
  339. Name, &getModule());
  340. }
  341. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
  342. unsigned NumTys) {
  343. return llvm::Intrinsic::getDeclaration(&getModule(),
  344. (llvm::Intrinsic::ID)IID, Tys, NumTys);
  345. }
  346. llvm::Function *CodeGenModule::getMemCpyFn() {
  347. if (MemCpyFn) return MemCpyFn;
  348. llvm::Intrinsic::ID IID;
  349. switch (Context.Target.getPointerWidth(0)) {
  350. default: assert(0 && "Unknown ptr width");
  351. case 32: IID = llvm::Intrinsic::memcpy_i32; break;
  352. case 64: IID = llvm::Intrinsic::memcpy_i64; break;
  353. }
  354. return MemCpyFn = getIntrinsic(IID);
  355. }
  356. llvm::Function *CodeGenModule::getMemSetFn() {
  357. if (MemSetFn) return MemSetFn;
  358. llvm::Intrinsic::ID IID;
  359. switch (Context.Target.getPointerWidth(0)) {
  360. default: assert(0 && "Unknown ptr width");
  361. case 32: IID = llvm::Intrinsic::memset_i32; break;
  362. case 64: IID = llvm::Intrinsic::memset_i64; break;
  363. }
  364. return MemSetFn = getIntrinsic(IID);
  365. }
  366. llvm::Constant *CodeGenModule::
  367. GetAddrOfConstantCFString(const std::string &str) {
  368. llvm::StringMapEntry<llvm::Constant *> &Entry =
  369. CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
  370. if (Entry.getValue())
  371. return Entry.getValue();
  372. std::vector<llvm::Constant*> Fields;
  373. if (!CFConstantStringClassRef) {
  374. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  375. Ty = llvm::ArrayType::get(Ty, 0);
  376. CFConstantStringClassRef =
  377. new llvm::GlobalVariable(Ty, false,
  378. llvm::GlobalVariable::ExternalLinkage, 0,
  379. "__CFConstantStringClassReference",
  380. &getModule());
  381. }
  382. // Class pointer.
  383. llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
  384. llvm::Constant *Zeros[] = { Zero, Zero };
  385. llvm::Constant *C =
  386. llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
  387. Fields.push_back(C);
  388. // Flags.
  389. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  390. Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
  391. // String pointer.
  392. C = llvm::ConstantArray::get(str);
  393. C = new llvm::GlobalVariable(C->getType(), true,
  394. llvm::GlobalValue::InternalLinkage,
  395. C, ".str", &getModule());
  396. C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
  397. Fields.push_back(C);
  398. // String length.
  399. Ty = getTypes().ConvertType(getContext().LongTy);
  400. Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
  401. // The struct.
  402. Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
  403. C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
  404. llvm::GlobalVariable *GV =
  405. new llvm::GlobalVariable(C->getType(), true,
  406. llvm::GlobalVariable::InternalLinkage,
  407. C, "", &getModule());
  408. GV->setSection("__DATA,__cfstring");
  409. Entry.setValue(GV);
  410. return GV;
  411. }
  412. /// GenerateWritableString -- Creates storage for a string literal.
  413. static llvm::Constant *GenerateStringLiteral(const std::string &str,
  414. bool constant,
  415. CodeGenModule &CGM) {
  416. // Create Constant for this string literal
  417. llvm::Constant *C=llvm::ConstantArray::get(str);
  418. // Create a global variable for this string
  419. C = new llvm::GlobalVariable(C->getType(), constant,
  420. llvm::GlobalValue::InternalLinkage,
  421. C, ".str", &CGM.getModule());
  422. return C;
  423. }
  424. /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
  425. /// array containing the literal. The result is pointer to array type.
  426. llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
  427. // Don't share any string literals if writable-strings is turned on.
  428. if (Features.WritableStrings)
  429. return GenerateStringLiteral(str, false, *this);
  430. llvm::StringMapEntry<llvm::Constant *> &Entry =
  431. ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
  432. if (Entry.getValue())
  433. return Entry.getValue();
  434. // Create a global variable for this.
  435. llvm::Constant *C = GenerateStringLiteral(str, true, *this);
  436. Entry.setValue(C);
  437. return C;
  438. }