CPPBackend.cpp 76 KB

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