CPPBackend.cpp 74 KB

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