CPPBackend.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  1. //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
  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 file implements the writing of the LLVM IR as a set of C++ calls to the
  11. // LLVM IR interface. The input module is assumed to be verified.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CPPTargetMachine.h"
  15. #include "llvm/CallingConv.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/InlineAsm.h"
  19. #include "llvm/Instruction.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/Module.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/PassManager.h"
  24. #include "llvm/TypeSymbolTable.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/FormattedStream.h"
  29. #include "llvm/Target/TargetRegistry.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include "llvm/Config/config.h"
  32. #include <algorithm>
  33. #include <set>
  34. using namespace llvm;
  35. static cl::opt<std::string>
  36. FuncName("cppfname", cl::desc("Specify the name of the generated function"),
  37. cl::value_desc("function name"));
  38. enum WhatToGenerate {
  39. GenProgram,
  40. GenModule,
  41. GenContents,
  42. GenFunction,
  43. GenFunctions,
  44. GenInline,
  45. GenVariable,
  46. GenType
  47. };
  48. static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
  49. cl::desc("Choose what kind of output to generate"),
  50. cl::init(GenProgram),
  51. cl::values(
  52. clEnumValN(GenProgram, "program", "Generate a complete program"),
  53. clEnumValN(GenModule, "module", "Generate a module definition"),
  54. clEnumValN(GenContents, "contents", "Generate contents of a module"),
  55. clEnumValN(GenFunction, "function", "Generate a function definition"),
  56. clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
  57. clEnumValN(GenInline, "inline", "Generate an inline function"),
  58. clEnumValN(GenVariable, "variable", "Generate a variable definition"),
  59. clEnumValN(GenType, "type", "Generate a type definition"),
  60. clEnumValEnd
  61. )
  62. );
  63. static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
  64. cl::desc("Specify the name of the thing to generate"),
  65. cl::init("!bad!"));
  66. extern "C" void LLVMInitializeCppBackendTarget() {
  67. // Register the target.
  68. RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
  69. }
  70. namespace {
  71. typedef std::vector<const Type*> TypeList;
  72. typedef std::map<const Type*,std::string> TypeMap;
  73. typedef std::map<const Value*,std::string> ValueMap;
  74. typedef std::set<std::string> NameSet;
  75. typedef std::set<const Type*> TypeSet;
  76. typedef std::set<const Value*> ValueSet;
  77. typedef std::map<const Value*,std::string> ForwardRefMap;
  78. /// CppWriter - This class is the main chunk of code that converts an LLVM
  79. /// module to a C++ translation unit.
  80. class CppWriter : public ModulePass {
  81. formatted_raw_ostream &Out;
  82. const Module *TheModule;
  83. uint64_t uniqueNum;
  84. TypeMap TypeNames;
  85. ValueMap ValueNames;
  86. TypeMap UnresolvedTypes;
  87. TypeList TypeStack;
  88. NameSet UsedNames;
  89. TypeSet DefinedTypes;
  90. ValueSet DefinedValues;
  91. ForwardRefMap ForwardRefs;
  92. bool is_inline;
  93. public:
  94. static char ID;
  95. explicit CppWriter(formatted_raw_ostream &o) :
  96. ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
  97. virtual const char *getPassName() const { return "C++ backend"; }
  98. bool runOnModule(Module &M);
  99. void printProgram(const std::string& fname, const std::string& modName );
  100. void printModule(const std::string& fname, const std::string& modName );
  101. void printContents(const std::string& fname, const std::string& modName );
  102. void printFunction(const std::string& fname, const std::string& funcName );
  103. void printFunctions();
  104. void printInline(const std::string& fname, const std::string& funcName );
  105. void printVariable(const std::string& fname, const std::string& varName );
  106. void printType(const std::string& fname, const std::string& typeName );
  107. void error(const std::string& msg);
  108. private:
  109. void printLinkageType(GlobalValue::LinkageTypes LT);
  110. void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
  111. void printCallingConv(CallingConv::ID cc);
  112. void printEscapedString(const std::string& str);
  113. void printCFP(const ConstantFP* CFP);
  114. std::string getCppName(const Type* val);
  115. inline void printCppName(const Type* val);
  116. std::string getCppName(const Value* val);
  117. inline void printCppName(const Value* val);
  118. void printAttributes(const AttrListPtr &PAL, const std::string &name);
  119. bool printTypeInternal(const Type* Ty);
  120. inline void printType(const Type* Ty);
  121. void printTypes(const Module* M);
  122. void printConstant(const Constant *CPV);
  123. void printConstants(const Module* M);
  124. void printVariableUses(const GlobalVariable *GV);
  125. void printVariableHead(const GlobalVariable *GV);
  126. void printVariableBody(const GlobalVariable *GV);
  127. void printFunctionUses(const Function *F);
  128. void printFunctionHead(const Function *F);
  129. void printFunctionBody(const Function *F);
  130. void printInstruction(const Instruction *I, const std::string& bbname);
  131. std::string getOpName(Value*);
  132. void printModuleBody();
  133. };
  134. static unsigned indent_level = 0;
  135. inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
  136. Out << "\n";
  137. if (delta >= 0 || indent_level >= unsigned(-delta))
  138. indent_level += delta;
  139. for (unsigned i = 0; i < indent_level; ++i)
  140. Out << " ";
  141. return Out;
  142. }
  143. inline void in() { indent_level++; }
  144. inline void out() { if (indent_level >0) indent_level--; }
  145. inline void
  146. sanitize(std::string& str) {
  147. for (size_t i = 0; i < str.length(); ++i)
  148. if (!isalnum(str[i]) && str[i] != '_')
  149. str[i] = '_';
  150. }
  151. inline std::string
  152. getTypePrefix(const Type* Ty ) {
  153. switch (Ty->getTypeID()) {
  154. case Type::VoidTyID: return "void_";
  155. case Type::IntegerTyID:
  156. return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
  157. "_";
  158. case Type::FloatTyID: return "float_";
  159. case Type::DoubleTyID: return "double_";
  160. case Type::LabelTyID: return "label_";
  161. case Type::FunctionTyID: return "func_";
  162. case Type::StructTyID: return "struct_";
  163. case Type::ArrayTyID: return "array_";
  164. case Type::PointerTyID: return "ptr_";
  165. case Type::VectorTyID: return "packed_";
  166. case Type::OpaqueTyID: return "opaque_";
  167. default: return "other_";
  168. }
  169. return "unknown_";
  170. }
  171. // Looks up the type in the symbol table and returns a pointer to its name or
  172. // a null pointer if it wasn't found. Note that this isn't the same as the
  173. // Mode::getTypeName function which will return an empty string, not a null
  174. // pointer if the name is not found.
  175. inline const std::string*
  176. findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
  177. TypeSymbolTable::const_iterator TI = ST.begin();
  178. TypeSymbolTable::const_iterator TE = ST.end();
  179. for (;TI != TE; ++TI)
  180. if (TI->second == Ty)
  181. return &(TI->first);
  182. return 0;
  183. }
  184. void CppWriter::error(const std::string& msg) {
  185. report_fatal_error(msg);
  186. }
  187. // printCFP - Print a floating point constant .. very carefully :)
  188. // This makes sure that conversion to/from floating yields the same binary
  189. // result so that we don't lose precision.
  190. void CppWriter::printCFP(const ConstantFP *CFP) {
  191. bool ignored;
  192. APFloat APF = APFloat(CFP->getValueAPF()); // copy
  193. if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
  194. APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
  195. Out << "ConstantFP::get(mod->getContext(), ";
  196. Out << "APFloat(";
  197. #if HAVE_PRINTF_A
  198. char Buffer[100];
  199. sprintf(Buffer, "%A", APF.convertToDouble());
  200. if ((!strncmp(Buffer, "0x", 2) ||
  201. !strncmp(Buffer, "-0x", 3) ||
  202. !strncmp(Buffer, "+0x", 3)) &&
  203. APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
  204. if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
  205. Out << "BitsToDouble(" << Buffer << ")";
  206. else
  207. Out << "BitsToFloat((float)" << Buffer << ")";
  208. Out << ")";
  209. } else {
  210. #endif
  211. std::string StrVal = ftostr(CFP->getValueAPF());
  212. while (StrVal[0] == ' ')
  213. StrVal.erase(StrVal.begin());
  214. // Check to make sure that the stringized number is not some string like
  215. // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
  216. if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
  217. ((StrVal[0] == '-' || StrVal[0] == '+') &&
  218. (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
  219. (CFP->isExactlyValue(atof(StrVal.c_str())))) {
  220. if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
  221. Out << StrVal;
  222. else
  223. Out << StrVal << "f";
  224. } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
  225. Out << "BitsToDouble(0x"
  226. << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
  227. << "ULL) /* " << StrVal << " */";
  228. else
  229. Out << "BitsToFloat(0x"
  230. << utohexstr((uint32_t)CFP->getValueAPF().
  231. bitcastToAPInt().getZExtValue())
  232. << "U) /* " << StrVal << " */";
  233. Out << ")";
  234. #if HAVE_PRINTF_A
  235. }
  236. #endif
  237. Out << ")";
  238. }
  239. void CppWriter::printCallingConv(CallingConv::ID cc){
  240. // Print the calling convention.
  241. switch (cc) {
  242. case CallingConv::C: Out << "CallingConv::C"; break;
  243. case CallingConv::Fast: Out << "CallingConv::Fast"; break;
  244. case CallingConv::Cold: Out << "CallingConv::Cold"; break;
  245. case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
  246. default: Out << cc; break;
  247. }
  248. }
  249. void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
  250. switch (LT) {
  251. case GlobalValue::InternalLinkage:
  252. Out << "GlobalValue::InternalLinkage"; break;
  253. case GlobalValue::PrivateLinkage:
  254. Out << "GlobalValue::PrivateLinkage"; break;
  255. case GlobalValue::LinkerPrivateLinkage:
  256. Out << "GlobalValue::LinkerPrivateLinkage"; break;
  257. case GlobalValue::AvailableExternallyLinkage:
  258. Out << "GlobalValue::AvailableExternallyLinkage "; break;
  259. case GlobalValue::LinkOnceAnyLinkage:
  260. Out << "GlobalValue::LinkOnceAnyLinkage "; break;
  261. case GlobalValue::LinkOnceODRLinkage:
  262. Out << "GlobalValue::LinkOnceODRLinkage "; break;
  263. case GlobalValue::WeakAnyLinkage:
  264. Out << "GlobalValue::WeakAnyLinkage"; break;
  265. case GlobalValue::WeakODRLinkage:
  266. Out << "GlobalValue::WeakODRLinkage"; break;
  267. case GlobalValue::AppendingLinkage:
  268. Out << "GlobalValue::AppendingLinkage"; break;
  269. case GlobalValue::ExternalLinkage:
  270. Out << "GlobalValue::ExternalLinkage"; break;
  271. case GlobalValue::DLLImportLinkage:
  272. Out << "GlobalValue::DLLImportLinkage"; break;
  273. case GlobalValue::DLLExportLinkage:
  274. Out << "GlobalValue::DLLExportLinkage"; break;
  275. case GlobalValue::ExternalWeakLinkage:
  276. Out << "GlobalValue::ExternalWeakLinkage"; break;
  277. case GlobalValue::CommonLinkage:
  278. Out << "GlobalValue::CommonLinkage"; break;
  279. }
  280. }
  281. void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
  282. switch (VisType) {
  283. default: llvm_unreachable("Unknown GVar visibility");
  284. case GlobalValue::DefaultVisibility:
  285. Out << "GlobalValue::DefaultVisibility";
  286. break;
  287. case GlobalValue::HiddenVisibility:
  288. Out << "GlobalValue::HiddenVisibility";
  289. break;
  290. case GlobalValue::ProtectedVisibility:
  291. Out << "GlobalValue::ProtectedVisibility";
  292. break;
  293. }
  294. }
  295. // printEscapedString - Print each character of the specified string, escaping
  296. // it if it is not printable or if it is an escape char.
  297. void CppWriter::printEscapedString(const std::string &Str) {
  298. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  299. unsigned char C = Str[i];
  300. if (isprint(C) && C != '"' && C != '\\') {
  301. Out << C;
  302. } else {
  303. Out << "\\x"
  304. << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
  305. << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
  306. }
  307. }
  308. }
  309. std::string CppWriter::getCppName(const Type* Ty) {
  310. // First, handle the primitive types .. easy
  311. if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
  312. switch (Ty->getTypeID()) {
  313. case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
  314. case Type::IntegerTyID: {
  315. unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
  316. return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
  317. }
  318. case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
  319. case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
  320. case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
  321. case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
  322. default:
  323. error("Invalid primitive type");
  324. break;
  325. }
  326. // shouldn't be returned, but make it sensible
  327. return "Type::getVoidTy(mod->getContext())";
  328. }
  329. // Now, see if we've seen the type before and return that
  330. TypeMap::iterator I = TypeNames.find(Ty);
  331. if (I != TypeNames.end())
  332. return I->second;
  333. // Okay, let's build a new name for this type. Start with a prefix
  334. const char* prefix = 0;
  335. switch (Ty->getTypeID()) {
  336. case Type::FunctionTyID: prefix = "FuncTy_"; break;
  337. case Type::StructTyID: prefix = "StructTy_"; break;
  338. case Type::ArrayTyID: prefix = "ArrayTy_"; break;
  339. case Type::PointerTyID: prefix = "PointerTy_"; break;
  340. case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
  341. case Type::VectorTyID: prefix = "VectorTy_"; break;
  342. default: prefix = "OtherTy_"; break; // prevent breakage
  343. }
  344. // See if the type has a name in the symboltable and build accordingly
  345. const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
  346. std::string name;
  347. if (tName)
  348. name = std::string(prefix) + *tName;
  349. else
  350. name = std::string(prefix) + utostr(uniqueNum++);
  351. sanitize(name);
  352. // Save the name
  353. return TypeNames[Ty] = name;
  354. }
  355. void CppWriter::printCppName(const Type* Ty) {
  356. printEscapedString(getCppName(Ty));
  357. }
  358. std::string CppWriter::getCppName(const Value* val) {
  359. std::string name;
  360. ValueMap::iterator I = ValueNames.find(val);
  361. if (I != ValueNames.end() && I->first == val)
  362. return I->second;
  363. if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
  364. name = std::string("gvar_") +
  365. getTypePrefix(GV->getType()->getElementType());
  366. } else if (isa<Function>(val)) {
  367. name = std::string("func_");
  368. } else if (const Constant* C = dyn_cast<Constant>(val)) {
  369. name = std::string("const_") + getTypePrefix(C->getType());
  370. } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
  371. if (is_inline) {
  372. unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
  373. Function::const_arg_iterator(Arg)) + 1;
  374. name = std::string("arg_") + utostr(argNum);
  375. NameSet::iterator NI = UsedNames.find(name);
  376. if (NI != UsedNames.end())
  377. name += std::string("_") + utostr(uniqueNum++);
  378. UsedNames.insert(name);
  379. return ValueNames[val] = name;
  380. } else {
  381. name = getTypePrefix(val->getType());
  382. }
  383. } else {
  384. name = getTypePrefix(val->getType());
  385. }
  386. if (val->hasName())
  387. name += val->getName();
  388. else
  389. name += utostr(uniqueNum++);
  390. sanitize(name);
  391. NameSet::iterator NI = UsedNames.find(name);
  392. if (NI != UsedNames.end())
  393. name += std::string("_") + utostr(uniqueNum++);
  394. UsedNames.insert(name);
  395. return ValueNames[val] = name;
  396. }
  397. void CppWriter::printCppName(const Value* val) {
  398. printEscapedString(getCppName(val));
  399. }
  400. void CppWriter::printAttributes(const AttrListPtr &PAL,
  401. const std::string &name) {
  402. Out << "AttrListPtr " << name << "_PAL;";
  403. nl(Out);
  404. if (!PAL.isEmpty()) {
  405. Out << '{'; in(); nl(Out);
  406. Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
  407. Out << "AttributeWithIndex PAWI;"; nl(Out);
  408. for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
  409. unsigned index = PAL.getSlot(i).Index;
  410. Attributes attrs = PAL.getSlot(i).Attrs;
  411. Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
  412. #define HANDLE_ATTR(X) \
  413. if (attrs & Attribute::X) \
  414. Out << " | Attribute::" #X; \
  415. attrs &= ~Attribute::X;
  416. HANDLE_ATTR(SExt);
  417. HANDLE_ATTR(ZExt);
  418. HANDLE_ATTR(NoReturn);
  419. HANDLE_ATTR(InReg);
  420. HANDLE_ATTR(StructRet);
  421. HANDLE_ATTR(NoUnwind);
  422. HANDLE_ATTR(NoAlias);
  423. HANDLE_ATTR(ByVal);
  424. HANDLE_ATTR(Nest);
  425. HANDLE_ATTR(ReadNone);
  426. HANDLE_ATTR(ReadOnly);
  427. HANDLE_ATTR(InlineHint);
  428. HANDLE_ATTR(NoInline);
  429. HANDLE_ATTR(AlwaysInline);
  430. HANDLE_ATTR(OptimizeForSize);
  431. HANDLE_ATTR(StackProtect);
  432. HANDLE_ATTR(StackProtectReq);
  433. HANDLE_ATTR(NoCapture);
  434. #undef HANDLE_ATTR
  435. assert(attrs == 0 && "Unhandled attribute!");
  436. Out << ";";
  437. nl(Out);
  438. Out << "Attrs.push_back(PAWI);";
  439. nl(Out);
  440. }
  441. Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
  442. nl(Out);
  443. out(); nl(Out);
  444. Out << '}'; nl(Out);
  445. }
  446. }
  447. bool CppWriter::printTypeInternal(const Type* Ty) {
  448. // We don't print definitions for primitive types
  449. if (Ty->isPrimitiveType() || Ty->isIntegerTy())
  450. return false;
  451. // If we already defined this type, we don't need to define it again.
  452. if (DefinedTypes.find(Ty) != DefinedTypes.end())
  453. return false;
  454. // Everything below needs the name for the type so get it now.
  455. std::string typeName(getCppName(Ty));
  456. // Search the type stack for recursion. If we find it, then generate this
  457. // as an OpaqueType, but make sure not to do this multiple times because
  458. // the type could appear in multiple places on the stack. Once the opaque
  459. // definition is issued, it must not be re-issued. Consequently we have to
  460. // check the UnresolvedTypes list as well.
  461. TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
  462. Ty);
  463. if (TI != TypeStack.end()) {
  464. TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
  465. if (I == UnresolvedTypes.end()) {
  466. Out << "PATypeHolder " << typeName;
  467. Out << "_fwd = OpaqueType::get(mod->getContext());";
  468. nl(Out);
  469. UnresolvedTypes[Ty] = typeName;
  470. }
  471. return true;
  472. }
  473. // We're going to print a derived type which, by definition, contains other
  474. // types. So, push this one we're printing onto the type stack to assist with
  475. // recursive definitions.
  476. TypeStack.push_back(Ty);
  477. // Print the type definition
  478. switch (Ty->getTypeID()) {
  479. case Type::FunctionTyID: {
  480. const FunctionType* FT = cast<FunctionType>(Ty);
  481. Out << "std::vector<const Type*>" << typeName << "_args;";
  482. nl(Out);
  483. FunctionType::param_iterator PI = FT->param_begin();
  484. FunctionType::param_iterator PE = FT->param_end();
  485. for (; PI != PE; ++PI) {
  486. const Type* argTy = static_cast<const Type*>(*PI);
  487. bool isForward = printTypeInternal(argTy);
  488. std::string argName(getCppName(argTy));
  489. Out << typeName << "_args.push_back(" << argName;
  490. if (isForward)
  491. Out << "_fwd";
  492. Out << ");";
  493. nl(Out);
  494. }
  495. bool isForward = printTypeInternal(FT->getReturnType());
  496. std::string retTypeName(getCppName(FT->getReturnType()));
  497. Out << "FunctionType* " << typeName << " = FunctionType::get(";
  498. in(); nl(Out) << "/*Result=*/" << retTypeName;
  499. if (isForward)
  500. Out << "_fwd";
  501. Out << ",";
  502. nl(Out) << "/*Params=*/" << typeName << "_args,";
  503. nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
  504. out();
  505. nl(Out);
  506. break;
  507. }
  508. case Type::StructTyID: {
  509. const StructType* ST = cast<StructType>(Ty);
  510. Out << "std::vector<const Type*>" << typeName << "_fields;";
  511. nl(Out);
  512. StructType::element_iterator EI = ST->element_begin();
  513. StructType::element_iterator EE = ST->element_end();
  514. for (; EI != EE; ++EI) {
  515. const Type* fieldTy = static_cast<const Type*>(*EI);
  516. bool isForward = printTypeInternal(fieldTy);
  517. std::string fieldName(getCppName(fieldTy));
  518. Out << typeName << "_fields.push_back(" << fieldName;
  519. if (isForward)
  520. Out << "_fwd";
  521. Out << ");";
  522. nl(Out);
  523. }
  524. Out << "StructType* " << typeName << " = StructType::get("
  525. << "mod->getContext(), "
  526. << typeName << "_fields, /*isPacked=*/"
  527. << (ST->isPacked() ? "true" : "false") << ");";
  528. nl(Out);
  529. break;
  530. }
  531. case Type::ArrayTyID: {
  532. const ArrayType* AT = cast<ArrayType>(Ty);
  533. const Type* ET = AT->getElementType();
  534. bool isForward = printTypeInternal(ET);
  535. std::string elemName(getCppName(ET));
  536. Out << "ArrayType* " << typeName << " = ArrayType::get("
  537. << elemName << (isForward ? "_fwd" : "")
  538. << ", " << utostr(AT->getNumElements()) << ");";
  539. nl(Out);
  540. break;
  541. }
  542. case Type::PointerTyID: {
  543. const PointerType* PT = cast<PointerType>(Ty);
  544. const Type* ET = PT->getElementType();
  545. bool isForward = printTypeInternal(ET);
  546. std::string elemName(getCppName(ET));
  547. Out << "PointerType* " << typeName << " = PointerType::get("
  548. << elemName << (isForward ? "_fwd" : "")
  549. << ", " << utostr(PT->getAddressSpace()) << ");";
  550. nl(Out);
  551. break;
  552. }
  553. case Type::VectorTyID: {
  554. const VectorType* PT = cast<VectorType>(Ty);
  555. const Type* ET = PT->getElementType();
  556. bool isForward = printTypeInternal(ET);
  557. std::string elemName(getCppName(ET));
  558. Out << "VectorType* " << typeName << " = VectorType::get("
  559. << elemName << (isForward ? "_fwd" : "")
  560. << ", " << utostr(PT->getNumElements()) << ");";
  561. nl(Out);
  562. break;
  563. }
  564. case Type::OpaqueTyID: {
  565. Out << "OpaqueType* " << typeName;
  566. Out << " = OpaqueType::get(mod->getContext());";
  567. nl(Out);
  568. break;
  569. }
  570. default:
  571. error("Invalid TypeID");
  572. }
  573. // If the type had a name, make sure we recreate it.
  574. const std::string* progTypeName =
  575. findTypeName(TheModule->getTypeSymbolTable(),Ty);
  576. if (progTypeName) {
  577. Out << "mod->addTypeName(\"" << *progTypeName << "\", "
  578. << typeName << ");";
  579. nl(Out);
  580. }
  581. // Pop us off the type stack
  582. TypeStack.pop_back();
  583. // Indicate that this type is now defined.
  584. DefinedTypes.insert(Ty);
  585. // Early resolve as many unresolved types as possible. Search the unresolved
  586. // types map for the type we just printed. Now that its definition is complete
  587. // we can resolve any previous references to it. This prevents a cascade of
  588. // unresolved types.
  589. TypeMap::iterator I = UnresolvedTypes.find(Ty);
  590. if (I != UnresolvedTypes.end()) {
  591. Out << "cast<OpaqueType>(" << I->second
  592. << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
  593. nl(Out);
  594. Out << I->second << " = cast<";
  595. switch (Ty->getTypeID()) {
  596. case Type::FunctionTyID: Out << "FunctionType"; break;
  597. case Type::ArrayTyID: Out << "ArrayType"; break;
  598. case Type::StructTyID: Out << "StructType"; break;
  599. case Type::VectorTyID: Out << "VectorType"; break;
  600. case Type::PointerTyID: Out << "PointerType"; break;
  601. case Type::OpaqueTyID: Out << "OpaqueType"; break;
  602. default: Out << "NoSuchDerivedType"; break;
  603. }
  604. Out << ">(" << I->second << "_fwd.get());";
  605. nl(Out); nl(Out);
  606. UnresolvedTypes.erase(I);
  607. }
  608. // Finally, separate the type definition from other with a newline.
  609. nl(Out);
  610. // We weren't a recursive type
  611. return false;
  612. }
  613. // Prints a type definition. Returns true if it could not resolve all the
  614. // types in the definition but had to use a forward reference.
  615. void CppWriter::printType(const Type* Ty) {
  616. assert(TypeStack.empty());
  617. TypeStack.clear();
  618. printTypeInternal(Ty);
  619. assert(TypeStack.empty());
  620. }
  621. void CppWriter::printTypes(const Module* M) {
  622. // Walk the symbol table and print out all its types
  623. const TypeSymbolTable& symtab = M->getTypeSymbolTable();
  624. for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
  625. TI != TE; ++TI) {
  626. // For primitive types and types already defined, just add a name
  627. TypeMap::const_iterator TNI = TypeNames.find(TI->second);
  628. if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
  629. TNI != TypeNames.end()) {
  630. Out << "mod->addTypeName(\"";
  631. printEscapedString(TI->first);
  632. Out << "\", " << getCppName(TI->second) << ");";
  633. nl(Out);
  634. // For everything else, define the type
  635. } else {
  636. printType(TI->second);
  637. }
  638. }
  639. // Add all of the global variables to the value table...
  640. for (Module::const_global_iterator I = TheModule->global_begin(),
  641. E = TheModule->global_end(); I != E; ++I) {
  642. if (I->hasInitializer())
  643. printType(I->getInitializer()->getType());
  644. printType(I->getType());
  645. }
  646. // Add all the functions to the table
  647. for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
  648. FI != FE; ++FI) {
  649. printType(FI->getReturnType());
  650. printType(FI->getFunctionType());
  651. // Add all the function arguments
  652. for (Function::const_arg_iterator AI = FI->arg_begin(),
  653. AE = FI->arg_end(); AI != AE; ++AI) {
  654. printType(AI->getType());
  655. }
  656. // Add all of the basic blocks and instructions
  657. for (Function::const_iterator BB = FI->begin(),
  658. E = FI->end(); BB != E; ++BB) {
  659. printType(BB->getType());
  660. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
  661. ++I) {
  662. printType(I->getType());
  663. for (unsigned i = 0; i < I->getNumOperands(); ++i)
  664. printType(I->getOperand(i)->getType());
  665. }
  666. }
  667. }
  668. }
  669. // printConstant - Print out a constant pool entry...
  670. void CppWriter::printConstant(const Constant *CV) {
  671. // First, if the constant is actually a GlobalValue (variable or function)
  672. // or its already in the constant list then we've printed it already and we
  673. // can just return.
  674. if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
  675. return;
  676. std::string constName(getCppName(CV));
  677. std::string typeName(getCppName(CV->getType()));
  678. if (isa<GlobalValue>(CV)) {
  679. // Skip variables and functions, we emit them elsewhere
  680. return;
  681. }
  682. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  683. std::string constValue = CI->getValue().toString(10, true);
  684. Out << "ConstantInt* " << constName
  685. << " = ConstantInt::get(mod->getContext(), APInt("
  686. << cast<IntegerType>(CI->getType())->getBitWidth()
  687. << ", StringRef(\"" << constValue << "\"), 10));";
  688. } else if (isa<ConstantAggregateZero>(CV)) {
  689. Out << "ConstantAggregateZero* " << constName
  690. << " = ConstantAggregateZero::get(" << typeName << ");";
  691. } else if (isa<ConstantPointerNull>(CV)) {
  692. Out << "ConstantPointerNull* " << constName
  693. << " = ConstantPointerNull::get(" << typeName << ");";
  694. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  695. Out << "ConstantFP* " << constName << " = ";
  696. printCFP(CFP);
  697. Out << ";";
  698. } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
  699. if (CA->isString() &&
  700. CA->getType()->getElementType() ==
  701. Type::getInt8Ty(CA->getContext())) {
  702. Out << "Constant* " << constName <<
  703. " = ConstantArray::get(mod->getContext(), \"";
  704. std::string tmp = CA->getAsString();
  705. bool nullTerminate = false;
  706. if (tmp[tmp.length()-1] == 0) {
  707. tmp.erase(tmp.length()-1);
  708. nullTerminate = true;
  709. }
  710. printEscapedString(tmp);
  711. // Determine if we want null termination or not.
  712. if (nullTerminate)
  713. Out << "\", true"; // Indicate that the null terminator should be
  714. // added.
  715. else
  716. Out << "\", false";// No null terminator
  717. Out << ");";
  718. } else {
  719. Out << "std::vector<Constant*> " << constName << "_elems;";
  720. nl(Out);
  721. unsigned N = CA->getNumOperands();
  722. for (unsigned i = 0; i < N; ++i) {
  723. printConstant(CA->getOperand(i)); // recurse to print operands
  724. Out << constName << "_elems.push_back("
  725. << getCppName(CA->getOperand(i)) << ");";
  726. nl(Out);
  727. }
  728. Out << "Constant* " << constName << " = ConstantArray::get("
  729. << typeName << ", " << constName << "_elems);";
  730. }
  731. } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
  732. Out << "std::vector<Constant*> " << constName << "_fields;";
  733. nl(Out);
  734. unsigned N = CS->getNumOperands();
  735. for (unsigned i = 0; i < N; i++) {
  736. printConstant(CS->getOperand(i));
  737. Out << constName << "_fields.push_back("
  738. << getCppName(CS->getOperand(i)) << ");";
  739. nl(Out);
  740. }
  741. Out << "Constant* " << constName << " = ConstantStruct::get("
  742. << typeName << ", " << constName << "_fields);";
  743. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
  744. Out << "std::vector<Constant*> " << constName << "_elems;";
  745. nl(Out);
  746. unsigned N = CP->getNumOperands();
  747. for (unsigned i = 0; i < N; ++i) {
  748. printConstant(CP->getOperand(i));
  749. Out << constName << "_elems.push_back("
  750. << getCppName(CP->getOperand(i)) << ");";
  751. nl(Out);
  752. }
  753. Out << "Constant* " << constName << " = ConstantVector::get("
  754. << typeName << ", " << constName << "_elems);";
  755. } else if (isa<UndefValue>(CV)) {
  756. Out << "UndefValue* " << constName << " = UndefValue::get("
  757. << typeName << ");";
  758. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  759. if (CE->getOpcode() == Instruction::GetElementPtr) {
  760. Out << "std::vector<Constant*> " << constName << "_indices;";
  761. nl(Out);
  762. printConstant(CE->getOperand(0));
  763. for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
  764. printConstant(CE->getOperand(i));
  765. Out << constName << "_indices.push_back("
  766. << getCppName(CE->getOperand(i)) << ");";
  767. nl(Out);
  768. }
  769. Out << "Constant* " << constName
  770. << " = ConstantExpr::getGetElementPtr("
  771. << getCppName(CE->getOperand(0)) << ", "
  772. << "&" << constName << "_indices[0], "
  773. << constName << "_indices.size()"
  774. << ");";
  775. } else if (CE->isCast()) {
  776. printConstant(CE->getOperand(0));
  777. Out << "Constant* " << constName << " = ConstantExpr::getCast(";
  778. switch (CE->getOpcode()) {
  779. default: llvm_unreachable("Invalid cast opcode");
  780. case Instruction::Trunc: Out << "Instruction::Trunc"; break;
  781. case Instruction::ZExt: Out << "Instruction::ZExt"; break;
  782. case Instruction::SExt: Out << "Instruction::SExt"; break;
  783. case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
  784. case Instruction::FPExt: Out << "Instruction::FPExt"; break;
  785. case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
  786. case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
  787. case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
  788. case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
  789. case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
  790. case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
  791. case Instruction::BitCast: Out << "Instruction::BitCast"; break;
  792. }
  793. Out << ", " << getCppName(CE->getOperand(0)) << ", "
  794. << getCppName(CE->getType()) << ");";
  795. } else {
  796. unsigned N = CE->getNumOperands();
  797. for (unsigned i = 0; i < N; ++i ) {
  798. printConstant(CE->getOperand(i));
  799. }
  800. Out << "Constant* " << constName << " = ConstantExpr::";
  801. switch (CE->getOpcode()) {
  802. case Instruction::Add: Out << "getAdd("; break;
  803. case Instruction::FAdd: Out << "getFAdd("; break;
  804. case Instruction::Sub: Out << "getSub("; break;
  805. case Instruction::FSub: Out << "getFSub("; break;
  806. case Instruction::Mul: Out << "getMul("; break;
  807. case Instruction::FMul: Out << "getFMul("; break;
  808. case Instruction::UDiv: Out << "getUDiv("; break;
  809. case Instruction::SDiv: Out << "getSDiv("; break;
  810. case Instruction::FDiv: Out << "getFDiv("; break;
  811. case Instruction::URem: Out << "getURem("; break;
  812. case Instruction::SRem: Out << "getSRem("; break;
  813. case Instruction::FRem: Out << "getFRem("; break;
  814. case Instruction::And: Out << "getAnd("; break;
  815. case Instruction::Or: Out << "getOr("; break;
  816. case Instruction::Xor: Out << "getXor("; break;
  817. case Instruction::ICmp:
  818. Out << "getICmp(ICmpInst::ICMP_";
  819. switch (CE->getPredicate()) {
  820. case ICmpInst::ICMP_EQ: Out << "EQ"; break;
  821. case ICmpInst::ICMP_NE: Out << "NE"; break;
  822. case ICmpInst::ICMP_SLT: Out << "SLT"; break;
  823. case ICmpInst::ICMP_ULT: Out << "ULT"; break;
  824. case ICmpInst::ICMP_SGT: Out << "SGT"; break;
  825. case ICmpInst::ICMP_UGT: Out << "UGT"; break;
  826. case ICmpInst::ICMP_SLE: Out << "SLE"; break;
  827. case ICmpInst::ICMP_ULE: Out << "ULE"; break;
  828. case ICmpInst::ICMP_SGE: Out << "SGE"; break;
  829. case ICmpInst::ICMP_UGE: Out << "UGE"; break;
  830. default: error("Invalid ICmp Predicate");
  831. }
  832. break;
  833. case Instruction::FCmp:
  834. Out << "getFCmp(FCmpInst::FCMP_";
  835. switch (CE->getPredicate()) {
  836. case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
  837. case FCmpInst::FCMP_ORD: Out << "ORD"; break;
  838. case FCmpInst::FCMP_UNO: Out << "UNO"; break;
  839. case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
  840. case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
  841. case FCmpInst::FCMP_ONE: Out << "ONE"; break;
  842. case FCmpInst::FCMP_UNE: Out << "UNE"; break;
  843. case FCmpInst::FCMP_OLT: Out << "OLT"; break;
  844. case FCmpInst::FCMP_ULT: Out << "ULT"; break;
  845. case FCmpInst::FCMP_OGT: Out << "OGT"; break;
  846. case FCmpInst::FCMP_UGT: Out << "UGT"; break;
  847. case FCmpInst::FCMP_OLE: Out << "OLE"; break;
  848. case FCmpInst::FCMP_ULE: Out << "ULE"; break;
  849. case FCmpInst::FCMP_OGE: Out << "OGE"; break;
  850. case FCmpInst::FCMP_UGE: Out << "UGE"; break;
  851. case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
  852. default: error("Invalid FCmp Predicate");
  853. }
  854. break;
  855. case Instruction::Shl: Out << "getShl("; break;
  856. case Instruction::LShr: Out << "getLShr("; break;
  857. case Instruction::AShr: Out << "getAShr("; break;
  858. case Instruction::Select: Out << "getSelect("; break;
  859. case Instruction::ExtractElement: Out << "getExtractElement("; break;
  860. case Instruction::InsertElement: Out << "getInsertElement("; break;
  861. case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
  862. default:
  863. error("Invalid constant expression");
  864. break;
  865. }
  866. Out << getCppName(CE->getOperand(0));
  867. for (unsigned i = 1; i < CE->getNumOperands(); ++i)
  868. Out << ", " << getCppName(CE->getOperand(i));
  869. Out << ");";
  870. }
  871. } else {
  872. error("Bad Constant");
  873. Out << "Constant* " << constName << " = 0; ";
  874. }
  875. nl(Out);
  876. }
  877. void CppWriter::printConstants(const Module* M) {
  878. // Traverse all the global variables looking for constant initializers
  879. for (Module::const_global_iterator I = TheModule->global_begin(),
  880. E = TheModule->global_end(); I != E; ++I)
  881. if (I->hasInitializer())
  882. printConstant(I->getInitializer());
  883. // Traverse the LLVM functions looking for constants
  884. for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
  885. FI != FE; ++FI) {
  886. // Add all of the basic blocks and instructions
  887. for (Function::const_iterator BB = FI->begin(),
  888. E = FI->end(); BB != E; ++BB) {
  889. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
  890. ++I) {
  891. for (unsigned i = 0; i < I->getNumOperands(); ++i) {
  892. if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
  893. printConstant(C);
  894. }
  895. }
  896. }
  897. }
  898. }
  899. }
  900. void CppWriter::printVariableUses(const GlobalVariable *GV) {
  901. nl(Out) << "// Type Definitions";
  902. nl(Out);
  903. printType(GV->getType());
  904. if (GV->hasInitializer()) {
  905. Constant *Init = GV->getInitializer();
  906. printType(Init->getType());
  907. if (Function *F = dyn_cast<Function>(Init)) {
  908. nl(Out)<< "/ Function Declarations"; nl(Out);
  909. printFunctionHead(F);
  910. } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
  911. nl(Out) << "// Global Variable Declarations"; nl(Out);
  912. printVariableHead(gv);
  913. nl(Out) << "// Global Variable Definitions"; nl(Out);
  914. printVariableBody(gv);
  915. } else {
  916. nl(Out) << "// Constant Definitions"; nl(Out);
  917. printConstant(Init);
  918. }
  919. }
  920. }
  921. void CppWriter::printVariableHead(const GlobalVariable *GV) {
  922. nl(Out) << "GlobalVariable* " << getCppName(GV);
  923. if (is_inline) {
  924. Out << " = mod->getGlobalVariable(mod->getContext(), ";
  925. printEscapedString(GV->getName());
  926. Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
  927. nl(Out) << "if (!" << getCppName(GV) << ") {";
  928. in(); nl(Out) << getCppName(GV);
  929. }
  930. Out << " = new GlobalVariable(/*Module=*/*mod, ";
  931. nl(Out) << "/*Type=*/";
  932. printCppName(GV->getType()->getElementType());
  933. Out << ",";
  934. nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
  935. Out << ",";
  936. nl(Out) << "/*Linkage=*/";
  937. printLinkageType(GV->getLinkage());
  938. Out << ",";
  939. nl(Out) << "/*Initializer=*/0, ";
  940. if (GV->hasInitializer()) {
  941. Out << "// has initializer, specified below";
  942. }
  943. nl(Out) << "/*Name=*/\"";
  944. printEscapedString(GV->getName());
  945. Out << "\");";
  946. nl(Out);
  947. if (GV->hasSection()) {
  948. printCppName(GV);
  949. Out << "->setSection(\"";
  950. printEscapedString(GV->getSection());
  951. Out << "\");";
  952. nl(Out);
  953. }
  954. if (GV->getAlignment()) {
  955. printCppName(GV);
  956. Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
  957. nl(Out);
  958. }
  959. if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
  960. printCppName(GV);
  961. Out << "->setVisibility(";
  962. printVisibilityType(GV->getVisibility());
  963. Out << ");";
  964. nl(Out);
  965. }
  966. if (is_inline) {
  967. out(); Out << "}"; nl(Out);
  968. }
  969. }
  970. void CppWriter::printVariableBody(const GlobalVariable *GV) {
  971. if (GV->hasInitializer()) {
  972. printCppName(GV);
  973. Out << "->setInitializer(";
  974. Out << getCppName(GV->getInitializer()) << ");";
  975. nl(Out);
  976. }
  977. }
  978. std::string CppWriter::getOpName(Value* V) {
  979. if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
  980. return getCppName(V);
  981. // See if its alread in the map of forward references, if so just return the
  982. // name we already set up for it
  983. ForwardRefMap::const_iterator I = ForwardRefs.find(V);
  984. if (I != ForwardRefs.end())
  985. return I->second;
  986. // This is a new forward reference. Generate a unique name for it
  987. std::string result(std::string("fwdref_") + utostr(uniqueNum++));
  988. // Yes, this is a hack. An Argument is the smallest instantiable value that
  989. // we can make as a placeholder for the real value. We'll replace these
  990. // Argument instances later.
  991. Out << "Argument* " << result << " = new Argument("
  992. << getCppName(V->getType()) << ");";
  993. nl(Out);
  994. ForwardRefs[V] = result;
  995. return result;
  996. }
  997. // printInstruction - This member is called for each Instruction in a function.
  998. void CppWriter::printInstruction(const Instruction *I,
  999. const std::string& bbname) {
  1000. std::string iName(getCppName(I));
  1001. // Before we emit this instruction, we need to take care of generating any
  1002. // forward references. So, we get the names of all the operands in advance
  1003. std::string* opNames = new std::string[I->getNumOperands()];
  1004. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  1005. opNames[i] = getOpName(I->getOperand(i));
  1006. }
  1007. switch (I->getOpcode()) {
  1008. default:
  1009. error("Invalid instruction");
  1010. break;
  1011. case Instruction::Ret: {
  1012. const ReturnInst* ret = cast<ReturnInst>(I);
  1013. Out << "ReturnInst::Create(mod->getContext(), "
  1014. << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
  1015. break;
  1016. }
  1017. case Instruction::Br: {
  1018. const BranchInst* br = cast<BranchInst>(I);
  1019. Out << "BranchInst::Create(" ;
  1020. if (br->getNumOperands() == 3 ) {
  1021. Out << opNames[2] << ", "
  1022. << opNames[1] << ", "
  1023. << opNames[0] << ", ";
  1024. } else if (br->getNumOperands() == 1) {
  1025. Out << opNames[0] << ", ";
  1026. } else {
  1027. error("Branch with 2 operands?");
  1028. }
  1029. Out << bbname << ");";
  1030. break;
  1031. }
  1032. case Instruction::Switch: {
  1033. const SwitchInst *SI = cast<SwitchInst>(I);
  1034. Out << "SwitchInst* " << iName << " = SwitchInst::Create("
  1035. << opNames[0] << ", "
  1036. << opNames[1] << ", "
  1037. << SI->getNumCases() << ", " << bbname << ");";
  1038. nl(Out);
  1039. for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
  1040. Out << iName << "->addCase("
  1041. << opNames[i] << ", "
  1042. << opNames[i+1] << ");";
  1043. nl(Out);
  1044. }
  1045. break;
  1046. }
  1047. case Instruction::IndirectBr: {
  1048. const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
  1049. Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
  1050. << opNames[0] << ", " << IBI->getNumDestinations() << ");";
  1051. nl(Out);
  1052. for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
  1053. Out << iName << "->addDestination(" << opNames[i] << ");";
  1054. nl(Out);
  1055. }
  1056. break;
  1057. }
  1058. case Instruction::Invoke: {
  1059. const InvokeInst* inv = cast<InvokeInst>(I);
  1060. Out << "std::vector<Value*> " << iName << "_params;";
  1061. nl(Out);
  1062. for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
  1063. Out << iName << "_params.push_back("
  1064. << opNames[i] << ");";
  1065. nl(Out);
  1066. }
  1067. Out << "InvokeInst *" << iName << " = InvokeInst::Create("
  1068. << opNames[0] << ", "
  1069. << opNames[1] << ", "
  1070. << opNames[2] << ", "
  1071. << iName << "_params.begin(), " << iName << "_params.end(), \"";
  1072. printEscapedString(inv->getName());
  1073. Out << "\", " << bbname << ");";
  1074. nl(Out) << iName << "->setCallingConv(";
  1075. printCallingConv(inv->getCallingConv());
  1076. Out << ");";
  1077. printAttributes(inv->getAttributes(), iName);
  1078. Out << iName << "->setAttributes(" << iName << "_PAL);";
  1079. nl(Out);
  1080. break;
  1081. }
  1082. case Instruction::Unwind: {
  1083. Out << "new UnwindInst("
  1084. << bbname << ");";
  1085. break;
  1086. }
  1087. case Instruction::Unreachable: {
  1088. Out << "new UnreachableInst("
  1089. << "mod->getContext(), "
  1090. << bbname << ");";
  1091. break;
  1092. }
  1093. case Instruction::Add:
  1094. case Instruction::FAdd:
  1095. case Instruction::Sub:
  1096. case Instruction::FSub:
  1097. case Instruction::Mul:
  1098. case Instruction::FMul:
  1099. case Instruction::UDiv:
  1100. case Instruction::SDiv:
  1101. case Instruction::FDiv:
  1102. case Instruction::URem:
  1103. case Instruction::SRem:
  1104. case Instruction::FRem:
  1105. case Instruction::And:
  1106. case Instruction::Or:
  1107. case Instruction::Xor:
  1108. case Instruction::Shl:
  1109. case Instruction::LShr:
  1110. case Instruction::AShr:{
  1111. Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
  1112. switch (I->getOpcode()) {
  1113. case Instruction::Add: Out << "Instruction::Add"; break;
  1114. case Instruction::FAdd: Out << "Instruction::FAdd"; break;
  1115. case Instruction::Sub: Out << "Instruction::Sub"; break;
  1116. case Instruction::FSub: Out << "Instruction::FSub"; break;
  1117. case Instruction::Mul: Out << "Instruction::Mul"; break;
  1118. case Instruction::FMul: Out << "Instruction::FMul"; break;
  1119. case Instruction::UDiv:Out << "Instruction::UDiv"; break;
  1120. case Instruction::SDiv:Out << "Instruction::SDiv"; break;
  1121. case Instruction::FDiv:Out << "Instruction::FDiv"; break;
  1122. case Instruction::URem:Out << "Instruction::URem"; break;
  1123. case Instruction::SRem:Out << "Instruction::SRem"; break;
  1124. case Instruction::FRem:Out << "Instruction::FRem"; break;
  1125. case Instruction::And: Out << "Instruction::And"; break;
  1126. case Instruction::Or: Out << "Instruction::Or"; break;
  1127. case Instruction::Xor: Out << "Instruction::Xor"; break;
  1128. case Instruction::Shl: Out << "Instruction::Shl"; break;
  1129. case Instruction::LShr:Out << "Instruction::LShr"; break;
  1130. case Instruction::AShr:Out << "Instruction::AShr"; break;
  1131. default: Out << "Instruction::BadOpCode"; break;
  1132. }
  1133. Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
  1134. printEscapedString(I->getName());
  1135. Out << "\", " << bbname << ");";
  1136. break;
  1137. }
  1138. case Instruction::FCmp: {
  1139. Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
  1140. switch (cast<FCmpInst>(I)->getPredicate()) {
  1141. case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
  1142. case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
  1143. case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
  1144. case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
  1145. case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
  1146. case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
  1147. case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
  1148. case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
  1149. case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
  1150. case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
  1151. case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
  1152. case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
  1153. case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
  1154. case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
  1155. case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
  1156. case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
  1157. default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
  1158. }
  1159. Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
  1160. printEscapedString(I->getName());
  1161. Out << "\");";
  1162. break;
  1163. }
  1164. case Instruction::ICmp: {
  1165. Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
  1166. switch (cast<ICmpInst>(I)->getPredicate()) {
  1167. case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
  1168. case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
  1169. case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
  1170. case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
  1171. case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
  1172. case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
  1173. case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
  1174. case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
  1175. case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
  1176. case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
  1177. default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
  1178. }
  1179. Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
  1180. printEscapedString(I->getName());
  1181. Out << "\");";
  1182. break;
  1183. }
  1184. case Instruction::Alloca: {
  1185. const AllocaInst* allocaI = cast<AllocaInst>(I);
  1186. Out << "AllocaInst* " << iName << " = new AllocaInst("
  1187. << getCppName(allocaI->getAllocatedType()) << ", ";
  1188. if (allocaI->isArrayAllocation())
  1189. Out << opNames[0] << ", ";
  1190. Out << "\"";
  1191. printEscapedString(allocaI->getName());
  1192. Out << "\", " << bbname << ");";
  1193. if (allocaI->getAlignment())
  1194. nl(Out) << iName << "->setAlignment("
  1195. << allocaI->getAlignment() << ");";
  1196. break;
  1197. }
  1198. case Instruction::Load:{
  1199. const LoadInst* load = cast<LoadInst>(I);
  1200. Out << "LoadInst* " << iName << " = new LoadInst("
  1201. << opNames[0] << ", \"";
  1202. printEscapedString(load->getName());
  1203. Out << "\", " << (load->isVolatile() ? "true" : "false" )
  1204. << ", " << bbname << ");";
  1205. break;
  1206. }
  1207. case Instruction::Store: {
  1208. const StoreInst* store = cast<StoreInst>(I);
  1209. Out << " new StoreInst("
  1210. << opNames[0] << ", "
  1211. << opNames[1] << ", "
  1212. << (store->isVolatile() ? "true" : "false")
  1213. << ", " << bbname << ");";
  1214. break;
  1215. }
  1216. case Instruction::GetElementPtr: {
  1217. const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
  1218. if (gep->getNumOperands() <= 2) {
  1219. Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
  1220. << opNames[0];
  1221. if (gep->getNumOperands() == 2)
  1222. Out << ", " << opNames[1];
  1223. } else {
  1224. Out << "std::vector<Value*> " << iName << "_indices;";
  1225. nl(Out);
  1226. for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
  1227. Out << iName << "_indices.push_back("
  1228. << opNames[i] << ");";
  1229. nl(Out);
  1230. }
  1231. Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
  1232. << opNames[0] << ", " << iName << "_indices.begin(), "
  1233. << iName << "_indices.end()";
  1234. }
  1235. Out << ", \"";
  1236. printEscapedString(gep->getName());
  1237. Out << "\", " << bbname << ");";
  1238. break;
  1239. }
  1240. case Instruction::PHI: {
  1241. const PHINode* phi = cast<PHINode>(I);
  1242. Out << "PHINode* " << iName << " = PHINode::Create("
  1243. << getCppName(phi->getType()) << ", \"";
  1244. printEscapedString(phi->getName());
  1245. Out << "\", " << bbname << ");";
  1246. nl(Out) << iName << "->reserveOperandSpace("
  1247. << phi->getNumIncomingValues()
  1248. << ");";
  1249. nl(Out);
  1250. for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
  1251. Out << iName << "->addIncoming("
  1252. << opNames[i] << ", " << opNames[i+1] << ");";
  1253. nl(Out);
  1254. }
  1255. break;
  1256. }
  1257. case Instruction::Trunc:
  1258. case Instruction::ZExt:
  1259. case Instruction::SExt:
  1260. case Instruction::FPTrunc:
  1261. case Instruction::FPExt:
  1262. case Instruction::FPToUI:
  1263. case Instruction::FPToSI:
  1264. case Instruction::UIToFP:
  1265. case Instruction::SIToFP:
  1266. case Instruction::PtrToInt:
  1267. case Instruction::IntToPtr:
  1268. case Instruction::BitCast: {
  1269. const CastInst* cst = cast<CastInst>(I);
  1270. Out << "CastInst* " << iName << " = new ";
  1271. switch (I->getOpcode()) {
  1272. case Instruction::Trunc: Out << "TruncInst"; break;
  1273. case Instruction::ZExt: Out << "ZExtInst"; break;
  1274. case Instruction::SExt: Out << "SExtInst"; break;
  1275. case Instruction::FPTrunc: Out << "FPTruncInst"; break;
  1276. case Instruction::FPExt: Out << "FPExtInst"; break;
  1277. case Instruction::FPToUI: Out << "FPToUIInst"; break;
  1278. case Instruction::FPToSI: Out << "FPToSIInst"; break;
  1279. case Instruction::UIToFP: Out << "UIToFPInst"; break;
  1280. case Instruction::SIToFP: Out << "SIToFPInst"; break;
  1281. case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
  1282. case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
  1283. case Instruction::BitCast: Out << "BitCastInst"; break;
  1284. default: assert(!"Unreachable"); break;
  1285. }
  1286. Out << "(" << opNames[0] << ", "
  1287. << getCppName(cst->getType()) << ", \"";
  1288. printEscapedString(cst->getName());
  1289. Out << "\", " << bbname << ");";
  1290. break;
  1291. }
  1292. case Instruction::Call:{
  1293. const CallInst* call = cast<CallInst>(I);
  1294. if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
  1295. Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
  1296. << getCppName(ila->getFunctionType()) << ", \""
  1297. << ila->getAsmString() << "\", \""
  1298. << ila->getConstraintString() << "\","
  1299. << (ila->hasSideEffects() ? "true" : "false") << ");";
  1300. nl(Out);
  1301. }
  1302. if (call->getNumOperands() > 2) {
  1303. Out << "std::vector<Value*> " << iName << "_params;";
  1304. nl(Out);
  1305. for (unsigned i = 1; i < call->getNumOperands(); ++i) {
  1306. Out << iName << "_params.push_back(" << opNames[i] << ");";
  1307. nl(Out);
  1308. }
  1309. Out << "CallInst* " << iName << " = CallInst::Create("
  1310. << opNames[0] << ", " << iName << "_params.begin(), "
  1311. << iName << "_params.end(), \"";
  1312. } else if (call->getNumOperands() == 2) {
  1313. Out << "CallInst* " << iName << " = CallInst::Create("
  1314. << opNames[0] << ", " << opNames[1] << ", \"";
  1315. } else {
  1316. Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
  1317. << ", \"";
  1318. }
  1319. printEscapedString(call->getName());
  1320. Out << "\", " << bbname << ");";
  1321. nl(Out) << iName << "->setCallingConv(";
  1322. printCallingConv(call->getCallingConv());
  1323. Out << ");";
  1324. nl(Out) << iName << "->setTailCall("
  1325. << (call->isTailCall() ? "true":"false");
  1326. Out << ");";
  1327. printAttributes(call->getAttributes(), iName);
  1328. Out << iName << "->setAttributes(" << iName << "_PAL);";
  1329. nl(Out);
  1330. break;
  1331. }
  1332. case Instruction::Select: {
  1333. const SelectInst* sel = cast<SelectInst>(I);
  1334. Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
  1335. Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
  1336. printEscapedString(sel->getName());
  1337. Out << "\", " << bbname << ");";
  1338. break;
  1339. }
  1340. case Instruction::UserOp1:
  1341. /// FALL THROUGH
  1342. case Instruction::UserOp2: {
  1343. /// FIXME: What should be done here?
  1344. break;
  1345. }
  1346. case Instruction::VAArg: {
  1347. const VAArgInst* va = cast<VAArgInst>(I);
  1348. Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
  1349. << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
  1350. printEscapedString(va->getName());
  1351. Out << "\", " << bbname << ");";
  1352. break;
  1353. }
  1354. case Instruction::ExtractElement: {
  1355. const ExtractElementInst* eei = cast<ExtractElementInst>(I);
  1356. Out << "ExtractElementInst* " << getCppName(eei)
  1357. << " = new ExtractElementInst(" << opNames[0]
  1358. << ", " << opNames[1] << ", \"";
  1359. printEscapedString(eei->getName());
  1360. Out << "\", " << bbname << ");";
  1361. break;
  1362. }
  1363. case Instruction::InsertElement: {
  1364. const InsertElementInst* iei = cast<InsertElementInst>(I);
  1365. Out << "InsertElementInst* " << getCppName(iei)
  1366. << " = InsertElementInst::Create(" << opNames[0]
  1367. << ", " << opNames[1] << ", " << opNames[2] << ", \"";
  1368. printEscapedString(iei->getName());
  1369. Out << "\", " << bbname << ");";
  1370. break;
  1371. }
  1372. case Instruction::ShuffleVector: {
  1373. const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
  1374. Out << "ShuffleVectorInst* " << getCppName(svi)
  1375. << " = new ShuffleVectorInst(" << opNames[0]
  1376. << ", " << opNames[1] << ", " << opNames[2] << ", \"";
  1377. printEscapedString(svi->getName());
  1378. Out << "\", " << bbname << ");";
  1379. break;
  1380. }
  1381. case Instruction::ExtractValue: {
  1382. const ExtractValueInst *evi = cast<ExtractValueInst>(I);
  1383. Out << "std::vector<unsigned> " << iName << "_indices;";
  1384. nl(Out);
  1385. for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
  1386. Out << iName << "_indices.push_back("
  1387. << evi->idx_begin()[i] << ");";
  1388. nl(Out);
  1389. }
  1390. Out << "ExtractValueInst* " << getCppName(evi)
  1391. << " = ExtractValueInst::Create(" << opNames[0]
  1392. << ", "
  1393. << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
  1394. printEscapedString(evi->getName());
  1395. Out << "\", " << bbname << ");";
  1396. break;
  1397. }
  1398. case Instruction::InsertValue: {
  1399. const InsertValueInst *ivi = cast<InsertValueInst>(I);
  1400. Out << "std::vector<unsigned> " << iName << "_indices;";
  1401. nl(Out);
  1402. for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
  1403. Out << iName << "_indices.push_back("
  1404. << ivi->idx_begin()[i] << ");";
  1405. nl(Out);
  1406. }
  1407. Out << "InsertValueInst* " << getCppName(ivi)
  1408. << " = InsertValueInst::Create(" << opNames[0]
  1409. << ", " << opNames[1] << ", "
  1410. << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
  1411. printEscapedString(ivi->getName());
  1412. Out << "\", " << bbname << ");";
  1413. break;
  1414. }
  1415. }
  1416. DefinedValues.insert(I);
  1417. nl(Out);
  1418. delete [] opNames;
  1419. }
  1420. // Print out the types, constants and declarations needed by one function
  1421. void CppWriter::printFunctionUses(const Function* F) {
  1422. nl(Out) << "// Type Definitions"; nl(Out);
  1423. if (!is_inline) {
  1424. // Print the function's return type
  1425. printType(F->getReturnType());
  1426. // Print the function's function type
  1427. printType(F->getFunctionType());
  1428. // Print the types of each of the function's arguments
  1429. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  1430. AI != AE; ++AI) {
  1431. printType(AI->getType());
  1432. }
  1433. }
  1434. // Print type definitions for every type referenced by an instruction and
  1435. // make a note of any global values or constants that are referenced
  1436. SmallPtrSet<GlobalValue*,64> gvs;
  1437. SmallPtrSet<Constant*,64> consts;
  1438. for (Function::const_iterator BB = F->begin(), BE = F->end();
  1439. BB != BE; ++BB){
  1440. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  1441. I != E; ++I) {
  1442. // Print the type of the instruction itself
  1443. printType(I->getType());
  1444. // Print the type of each of the instruction's operands
  1445. for (unsigned i = 0; i < I->getNumOperands(); ++i) {
  1446. Value* operand = I->getOperand(i);
  1447. printType(operand->getType());
  1448. // If the operand references a GVal or Constant, make a note of it
  1449. if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
  1450. gvs.insert(GV);
  1451. if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  1452. if (GVar->hasInitializer())
  1453. consts.insert(GVar->getInitializer());
  1454. } else if (Constant* C = dyn_cast<Constant>(operand))
  1455. consts.insert(C);
  1456. }
  1457. }
  1458. }
  1459. // Print the function declarations for any functions encountered
  1460. nl(Out) << "// Function Declarations"; nl(Out);
  1461. for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
  1462. I != E; ++I) {
  1463. if (Function* Fun = dyn_cast<Function>(*I)) {
  1464. if (!is_inline || Fun != F)
  1465. printFunctionHead(Fun);
  1466. }
  1467. }
  1468. // Print the global variable declarations for any variables encountered
  1469. nl(Out) << "// Global Variable Declarations"; nl(Out);
  1470. for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
  1471. I != E; ++I) {
  1472. if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
  1473. printVariableHead(F);
  1474. }
  1475. // Print the constants found
  1476. nl(Out) << "// Constant Definitions"; nl(Out);
  1477. for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
  1478. E = consts.end(); I != E; ++I) {
  1479. printConstant(*I);
  1480. }
  1481. // Process the global variables definitions now that all the constants have
  1482. // been emitted. These definitions just couple the gvars with their constant
  1483. // initializers.
  1484. nl(Out) << "// Global Variable Definitions"; nl(Out);
  1485. for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
  1486. I != E; ++I) {
  1487. if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
  1488. printVariableBody(GV);
  1489. }
  1490. }
  1491. void CppWriter::printFunctionHead(const Function* F) {
  1492. nl(Out) << "Function* " << getCppName(F);
  1493. if (is_inline) {
  1494. Out << " = mod->getFunction(\"";
  1495. printEscapedString(F->getName());
  1496. Out << "\", " << getCppName(F->getFunctionType()) << ");";
  1497. nl(Out) << "if (!" << getCppName(F) << ") {";
  1498. nl(Out) << getCppName(F);
  1499. }
  1500. Out<< " = Function::Create(";
  1501. nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
  1502. nl(Out) << "/*Linkage=*/";
  1503. printLinkageType(F->getLinkage());
  1504. Out << ",";
  1505. nl(Out) << "/*Name=*/\"";
  1506. printEscapedString(F->getName());
  1507. Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
  1508. nl(Out,-1);
  1509. printCppName(F);
  1510. Out << "->setCallingConv(";
  1511. printCallingConv(F->getCallingConv());
  1512. Out << ");";
  1513. nl(Out);
  1514. if (F->hasSection()) {
  1515. printCppName(F);
  1516. Out << "->setSection(\"" << F->getSection() << "\");";
  1517. nl(Out);
  1518. }
  1519. if (F->getAlignment()) {
  1520. printCppName(F);
  1521. Out << "->setAlignment(" << F->getAlignment() << ");";
  1522. nl(Out);
  1523. }
  1524. if (F->getVisibility() != GlobalValue::DefaultVisibility) {
  1525. printCppName(F);
  1526. Out << "->setVisibility(";
  1527. printVisibilityType(F->getVisibility());
  1528. Out << ");";
  1529. nl(Out);
  1530. }
  1531. if (F->hasGC()) {
  1532. printCppName(F);
  1533. Out << "->setGC(\"" << F->getGC() << "\");";
  1534. nl(Out);
  1535. }
  1536. if (is_inline) {
  1537. Out << "}";
  1538. nl(Out);
  1539. }
  1540. printAttributes(F->getAttributes(), getCppName(F));
  1541. printCppName(F);
  1542. Out << "->setAttributes(" << getCppName(F) << "_PAL);";
  1543. nl(Out);
  1544. }
  1545. void CppWriter::printFunctionBody(const Function *F) {
  1546. if (F->isDeclaration())
  1547. return; // external functions have no bodies.
  1548. // Clear the DefinedValues and ForwardRefs maps because we can't have
  1549. // cross-function forward refs
  1550. ForwardRefs.clear();
  1551. DefinedValues.clear();
  1552. // Create all the argument values
  1553. if (!is_inline) {
  1554. if (!F->arg_empty()) {
  1555. Out << "Function::arg_iterator args = " << getCppName(F)
  1556. << "->arg_begin();";
  1557. nl(Out);
  1558. }
  1559. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  1560. AI != AE; ++AI) {
  1561. Out << "Value* " << getCppName(AI) << " = args++;";
  1562. nl(Out);
  1563. if (AI->hasName()) {
  1564. Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
  1565. nl(Out);
  1566. }
  1567. }
  1568. }
  1569. // Create all the basic blocks
  1570. nl(Out);
  1571. for (Function::const_iterator BI = F->begin(), BE = F->end();
  1572. BI != BE; ++BI) {
  1573. std::string bbname(getCppName(BI));
  1574. Out << "BasicBlock* " << bbname <<
  1575. " = BasicBlock::Create(mod->getContext(), \"";
  1576. if (BI->hasName())
  1577. printEscapedString(BI->getName());
  1578. Out << "\"," << getCppName(BI->getParent()) << ",0);";
  1579. nl(Out);
  1580. }
  1581. // Output all of its basic blocks... for the function
  1582. for (Function::const_iterator BI = F->begin(), BE = F->end();
  1583. BI != BE; ++BI) {
  1584. std::string bbname(getCppName(BI));
  1585. nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
  1586. nl(Out);
  1587. // Output all of the instructions in the basic block...
  1588. for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
  1589. I != E; ++I) {
  1590. printInstruction(I,bbname);
  1591. }
  1592. }
  1593. // Loop over the ForwardRefs and resolve them now that all instructions
  1594. // are generated.
  1595. if (!ForwardRefs.empty()) {
  1596. nl(Out) << "// Resolve Forward References";
  1597. nl(Out);
  1598. }
  1599. while (!ForwardRefs.empty()) {
  1600. ForwardRefMap::iterator I = ForwardRefs.begin();
  1601. Out << I->second << "->replaceAllUsesWith("
  1602. << getCppName(I->first) << "); delete " << I->second << ";";
  1603. nl(Out);
  1604. ForwardRefs.erase(I);
  1605. }
  1606. }
  1607. void CppWriter::printInline(const std::string& fname,
  1608. const std::string& func) {
  1609. const Function* F = TheModule->getFunction(func);
  1610. if (!F) {
  1611. error(std::string("Function '") + func + "' not found in input module");
  1612. return;
  1613. }
  1614. if (F->isDeclaration()) {
  1615. error(std::string("Function '") + func + "' is external!");
  1616. return;
  1617. }
  1618. nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
  1619. << getCppName(F);
  1620. unsigned arg_count = 1;
  1621. for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
  1622. AI != AE; ++AI) {
  1623. Out << ", Value* arg_" << arg_count;
  1624. }
  1625. Out << ") {";
  1626. nl(Out);
  1627. is_inline = true;
  1628. printFunctionUses(F);
  1629. printFunctionBody(F);
  1630. is_inline = false;
  1631. Out << "return " << getCppName(F->begin()) << ";";
  1632. nl(Out) << "}";
  1633. nl(Out);
  1634. }
  1635. void CppWriter::printModuleBody() {
  1636. // Print out all the type definitions
  1637. nl(Out) << "// Type Definitions"; nl(Out);
  1638. printTypes(TheModule);
  1639. // Functions can call each other and global variables can reference them so
  1640. // define all the functions first before emitting their function bodies.
  1641. nl(Out) << "// Function Declarations"; nl(Out);
  1642. for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
  1643. I != E; ++I)
  1644. printFunctionHead(I);
  1645. // Process the global variables declarations. We can't initialze them until
  1646. // after the constants are printed so just print a header for each global
  1647. nl(Out) << "// Global Variable Declarations\n"; nl(Out);
  1648. for (Module::const_global_iterator I = TheModule->global_begin(),
  1649. E = TheModule->global_end(); I != E; ++I) {
  1650. printVariableHead(I);
  1651. }
  1652. // Print out all the constants definitions. Constants don't recurse except
  1653. // through GlobalValues. All GlobalValues have been declared at this point
  1654. // so we can proceed to generate the constants.
  1655. nl(Out) << "// Constant Definitions"; nl(Out);
  1656. printConstants(TheModule);
  1657. // Process the global variables definitions now that all the constants have
  1658. // been emitted. These definitions just couple the gvars with their constant
  1659. // initializers.
  1660. nl(Out) << "// Global Variable Definitions"; nl(Out);
  1661. for (Module::const_global_iterator I = TheModule->global_begin(),
  1662. E = TheModule->global_end(); I != E; ++I) {
  1663. printVariableBody(I);
  1664. }
  1665. // Finally, we can safely put out all of the function bodies.
  1666. nl(Out) << "// Function Definitions"; nl(Out);
  1667. for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
  1668. I != E; ++I) {
  1669. if (!I->isDeclaration()) {
  1670. nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
  1671. << ")";
  1672. nl(Out) << "{";
  1673. nl(Out,1);
  1674. printFunctionBody(I);
  1675. nl(Out,-1) << "}";
  1676. nl(Out);
  1677. }
  1678. }
  1679. }
  1680. void CppWriter::printProgram(const std::string& fname,
  1681. const std::string& mName) {
  1682. Out << "#include <llvm/LLVMContext.h>\n";
  1683. Out << "#include <llvm/Module.h>\n";
  1684. Out << "#include <llvm/DerivedTypes.h>\n";
  1685. Out << "#include <llvm/Constants.h>\n";
  1686. Out << "#include <llvm/GlobalVariable.h>\n";
  1687. Out << "#include <llvm/Function.h>\n";
  1688. Out << "#include <llvm/CallingConv.h>\n";
  1689. Out << "#include <llvm/BasicBlock.h>\n";
  1690. Out << "#include <llvm/Instructions.h>\n";
  1691. Out << "#include <llvm/InlineAsm.h>\n";
  1692. Out << "#include <llvm/Support/FormattedStream.h>\n";
  1693. Out << "#include <llvm/Support/MathExtras.h>\n";
  1694. Out << "#include <llvm/Pass.h>\n";
  1695. Out << "#include <llvm/PassManager.h>\n";
  1696. Out << "#include <llvm/ADT/SmallVector.h>\n";
  1697. Out << "#include <llvm/Analysis/Verifier.h>\n";
  1698. Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
  1699. Out << "#include <algorithm>\n";
  1700. Out << "using namespace llvm;\n\n";
  1701. Out << "Module* " << fname << "();\n\n";
  1702. Out << "int main(int argc, char**argv) {\n";
  1703. Out << " Module* Mod = " << fname << "();\n";
  1704. Out << " verifyModule(*Mod, PrintMessageAction);\n";
  1705. Out << " PassManager PM;\n";
  1706. Out << " PM.add(createPrintModulePass(&outs()));\n";
  1707. Out << " PM.run(*Mod);\n";
  1708. Out << " return 0;\n";
  1709. Out << "}\n\n";
  1710. printModule(fname,mName);
  1711. }
  1712. void CppWriter::printModule(const std::string& fname,
  1713. const std::string& mName) {
  1714. nl(Out) << "Module* " << fname << "() {";
  1715. nl(Out,1) << "// Module Construction";
  1716. nl(Out) << "Module* mod = new Module(\"";
  1717. printEscapedString(mName);
  1718. Out << "\", getGlobalContext());";
  1719. if (!TheModule->getTargetTriple().empty()) {
  1720. nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
  1721. }
  1722. if (!TheModule->getTargetTriple().empty()) {
  1723. nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
  1724. << "\");";
  1725. }
  1726. if (!TheModule->getModuleInlineAsm().empty()) {
  1727. nl(Out) << "mod->setModuleInlineAsm(\"";
  1728. printEscapedString(TheModule->getModuleInlineAsm());
  1729. Out << "\");";
  1730. }
  1731. nl(Out);
  1732. // Loop over the dependent libraries and emit them.
  1733. Module::lib_iterator LI = TheModule->lib_begin();
  1734. Module::lib_iterator LE = TheModule->lib_end();
  1735. while (LI != LE) {
  1736. Out << "mod->addLibrary(\"" << *LI << "\");";
  1737. nl(Out);
  1738. ++LI;
  1739. }
  1740. printModuleBody();
  1741. nl(Out) << "return mod;";
  1742. nl(Out,-1) << "}";
  1743. nl(Out);
  1744. }
  1745. void CppWriter::printContents(const std::string& fname,
  1746. const std::string& mName) {
  1747. Out << "\nModule* " << fname << "(Module *mod) {\n";
  1748. Out << "\nmod->setModuleIdentifier(\"";
  1749. printEscapedString(mName);
  1750. Out << "\");\n";
  1751. printModuleBody();
  1752. Out << "\nreturn mod;\n";
  1753. Out << "\n}\n";
  1754. }
  1755. void CppWriter::printFunction(const std::string& fname,
  1756. const std::string& funcName) {
  1757. const Function* F = TheModule->getFunction(funcName);
  1758. if (!F) {
  1759. error(std::string("Function '") + funcName + "' not found in input module");
  1760. return;
  1761. }
  1762. Out << "\nFunction* " << fname << "(Module *mod) {\n";
  1763. printFunctionUses(F);
  1764. printFunctionHead(F);
  1765. printFunctionBody(F);
  1766. Out << "return " << getCppName(F) << ";\n";
  1767. Out << "}\n";
  1768. }
  1769. void CppWriter::printFunctions() {
  1770. const Module::FunctionListType &funcs = TheModule->getFunctionList();
  1771. Module::const_iterator I = funcs.begin();
  1772. Module::const_iterator IE = funcs.end();
  1773. for (; I != IE; ++I) {
  1774. const Function &func = *I;
  1775. if (!func.isDeclaration()) {
  1776. std::string name("define_");
  1777. name += func.getName();
  1778. printFunction(name, func.getName());
  1779. }
  1780. }
  1781. }
  1782. void CppWriter::printVariable(const std::string& fname,
  1783. const std::string& varName) {
  1784. const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
  1785. if (!GV) {
  1786. error(std::string("Variable '") + varName + "' not found in input module");
  1787. return;
  1788. }
  1789. Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
  1790. printVariableUses(GV);
  1791. printVariableHead(GV);
  1792. printVariableBody(GV);
  1793. Out << "return " << getCppName(GV) << ";\n";
  1794. Out << "}\n";
  1795. }
  1796. void CppWriter::printType(const std::string& fname,
  1797. const std::string& typeName) {
  1798. const Type* Ty = TheModule->getTypeByName(typeName);
  1799. if (!Ty) {
  1800. error(std::string("Type '") + typeName + "' not found in input module");
  1801. return;
  1802. }
  1803. Out << "\nType* " << fname << "(Module *mod) {\n";
  1804. printType(Ty);
  1805. Out << "return " << getCppName(Ty) << ";\n";
  1806. Out << "}\n";
  1807. }
  1808. bool CppWriter::runOnModule(Module &M) {
  1809. TheModule = &M;
  1810. // Emit a header
  1811. Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
  1812. // Get the name of the function we're supposed to generate
  1813. std::string fname = FuncName.getValue();
  1814. // Get the name of the thing we are to generate
  1815. std::string tgtname = NameToGenerate.getValue();
  1816. if (GenerationType == GenModule ||
  1817. GenerationType == GenContents ||
  1818. GenerationType == GenProgram ||
  1819. GenerationType == GenFunctions) {
  1820. if (tgtname == "!bad!") {
  1821. if (M.getModuleIdentifier() == "-")
  1822. tgtname = "<stdin>";
  1823. else
  1824. tgtname = M.getModuleIdentifier();
  1825. }
  1826. } else if (tgtname == "!bad!")
  1827. error("You must use the -for option with -gen-{function,variable,type}");
  1828. switch (WhatToGenerate(GenerationType)) {
  1829. case GenProgram:
  1830. if (fname.empty())
  1831. fname = "makeLLVMModule";
  1832. printProgram(fname,tgtname);
  1833. break;
  1834. case GenModule:
  1835. if (fname.empty())
  1836. fname = "makeLLVMModule";
  1837. printModule(fname,tgtname);
  1838. break;
  1839. case GenContents:
  1840. if (fname.empty())
  1841. fname = "makeLLVMModuleContents";
  1842. printContents(fname,tgtname);
  1843. break;
  1844. case GenFunction:
  1845. if (fname.empty())
  1846. fname = "makeLLVMFunction";
  1847. printFunction(fname,tgtname);
  1848. break;
  1849. case GenFunctions:
  1850. printFunctions();
  1851. break;
  1852. case GenInline:
  1853. if (fname.empty())
  1854. fname = "makeLLVMInline";
  1855. printInline(fname,tgtname);
  1856. break;
  1857. case GenVariable:
  1858. if (fname.empty())
  1859. fname = "makeLLVMVariable";
  1860. printVariable(fname,tgtname);
  1861. break;
  1862. case GenType:
  1863. if (fname.empty())
  1864. fname = "makeLLVMType";
  1865. printType(fname,tgtname);
  1866. break;
  1867. default:
  1868. error("Invalid generation option");
  1869. }
  1870. return false;
  1871. }
  1872. }
  1873. char CppWriter::ID = 0;
  1874. //===----------------------------------------------------------------------===//
  1875. // External Interface declaration
  1876. //===----------------------------------------------------------------------===//
  1877. bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
  1878. formatted_raw_ostream &o,
  1879. CodeGenFileType FileType,
  1880. CodeGenOpt::Level OptLevel,
  1881. bool DisableVerify) {
  1882. if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
  1883. PM.add(new CppWriter(o));
  1884. return false;
  1885. }