CPPBackend.cpp 73 KB

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