CodeGenModule.cpp 19 KB

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