CPPBackend.cpp 72 KB

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