CPPBackend.cpp 74 KB

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