CPPBackend.cpp 71 KB

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