CPPBackend.cpp 75 KB

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