blob: f9ddc7d8c419fb5ba8a4767842f5717d5bbbc470 [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002//
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00003// This library converts LLVM code to C code, compilable by GCC.
Chris Lattner16c7bb22002-05-09 02:28:59 +00004//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00005//===-----------------------------------------------------------------------==//
6#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00007#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +00008#include "llvm/DerivedTypes.h"
9#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000010#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000011#include "llvm/Pass.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000012#include "llvm/SymbolTable.h"
Chris Lattner3af3ba82002-05-09 21:31:18 +000013#include "llvm/SlotCalculator.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000014#include "llvm/Analysis/FindUsedTypes.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000015#include "llvm/Analysis/ConstantsScanner.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000016#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000017#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000018#include "Support/StringExtras.h"
19#include "Support/STLExtras.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000020#include <algorithm>
Chris Lattner78771c82002-05-17 04:55:35 +000021#include <set>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000022#include <sstream>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000023using std::string;
24using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000025using std::ostream;
26
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000027
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000028namespace {
Chris Lattner0e9f93e2002-08-31 00:29:16 +000029 class CWriter : public Pass, public InstVisitor<CWriter> {
30 ostream &Out;
31 SlotCalculator *Table;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000032 const Module *TheModule;
33 map<const Type *, string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +000034 std::set<const Value*> MangledGlobals;
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000035 bool needsMalloc;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000036
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000037 map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000038 public:
Chris Lattner0e9f93e2002-08-31 00:29:16 +000039 CWriter(ostream &o) : Out(o) {}
40
41 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.setPreservesAll();
43 AU.addRequired<FindUsedTypes>();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000044 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000045
46 virtual bool run(Module &M) {
47 // Initialize
48 Table = new SlotCalculator(&M, false);
49 TheModule = &M;
50
51 // Ensure that all structure types have names...
52 bool Changed = nameAllUsedStructureTypes(M);
53
54 // Run...
55 printModule(&M);
56
57 // Free memory...
58 delete Table;
59 TypeNames.clear();
60 MangledGlobals.clear();
61 return false;
62 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000063
Nick Hildenbrandt98502372002-11-18 20:55:50 +000064 ostream &printType(std::ostream &Out, const Type *Ty, const string &VariableName = "",
Vikram S. Adve969c4ad2002-08-25 20:00:08 +000065 bool IgnoreName = false, bool namedContext = true);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000066
Chris Lattnerbb03efd2002-06-25 15:57:03 +000067 void writeOperand(Value *Operand);
68 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000069
70 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000071
Chris Lattner4fbf26d2002-05-09 20:53:56 +000072 private :
Chris Lattner0e9f93e2002-08-31 00:29:16 +000073 bool nameAllUsedStructureTypes(Module &M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000074 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000075 void printSymbolTable(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +000076 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000077 void printGlobal(const GlobalVariable *GV);
Chris Lattner4cda8352002-08-20 16:55:48 +000078 void printFunctionSignature(const Function *F, bool Prototype);
79
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000080 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000081
Chris Lattner6d492922002-08-19 21:32:41 +000082 void printConstant(Constant *CPV);
83 void printConstantArray(ConstantArray *CPA);
84
Chris Lattnerd0c668c2002-05-09 21:18:38 +000085 // isInlinableInst - Attempt to inline instructions into their uses to build
86 // trees as much as possible. To do this, we have to consistently decide
87 // what is acceptable to inline, so that variable declarations don't get
88 // printed and an extra copy of the expr is not emitted.
89 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +000090 static bool isInlinableInst(const Instruction &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +000091 // Must be an expression, must be used exactly once. If it is dead, we
92 // emit it inline where it would go.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000093 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
Nick Hildenbrandt2cf2cbc2002-11-06 20:07:54 +000094 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
95 isa<LoadInst>(I)) // Don't inline a load across a store!
Chris Lattnerd0c668c2002-05-09 21:18:38 +000096 return false;
97
98 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000099 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000100 }
101
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000102 // Instruction visitation functions
103 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000104
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000105 void visitReturnInst(ReturnInst &I);
106 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000107 void visitSwitchInst(SwitchInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000108
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000109 void visitPHINode(PHINode &I) {}
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000110 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000111
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000112 void visitCastInst (CastInst &I);
113 void visitCallInst (CallInst &I);
114 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000115
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000116 void visitMallocInst(MallocInst &I);
117 void visitAllocaInst(AllocaInst &I);
118 void visitFreeInst (FreeInst &I);
119 void visitLoadInst (LoadInst &I);
120 void visitStoreInst (StoreInst &I);
121 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000122
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000123 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000124 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000125 abort();
126 }
127
128 void outputLValue(Instruction *I) {
129 Out << " " << getValueName(I) << " = ";
130 }
131 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
132 unsigned Indent);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000133 void printIndexingExpression(Value *Ptr, User::op_iterator I,
134 User::op_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000135 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000136}
137
Chris Lattner2f499022002-05-09 04:21:21 +0000138// We dont want identifier names with ., space, - in them.
139// So we replace them with _
140static string makeNameProper(string x) {
141 string tmp;
142 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
143 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000144 case '.': tmp += "d_"; break;
145 case ' ': tmp += "s_"; break;
146 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000147 default: tmp += *sI;
148 }
149
150 return tmp;
151}
152
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000153string CWriter::getValueName(const Value *V) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000154 if (V->hasName()) { // Print out the label if it exists...
155 if (isa<GlobalValue>(V) && // Do not mangle globals...
Chris Lattnera9f5e052003-04-22 20:19:52 +0000156 cast<GlobalValue>(V)->hasExternalLinkage()) // Unless it's internal or
157 //!MangledGlobals.count(V)) // Unless the name would collide if we don't
Chris Lattner2f499022002-05-09 04:21:21 +0000158 return makeNameProper(V->getName());
159
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000160 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
161 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000162 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000163
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000164 int Slot = Table->getValSlot(V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000165 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000166 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000167}
168
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000169// A pointer type should not use parens around *'s alone, e.g., (**)
170inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
171 return (NameSoFar.find_last_not_of('*') != std::string::npos);
172}
173
Chris Lattner83c57752002-08-19 22:17:53 +0000174// Pass the Type* and the variable name and this prints out the variable
175// declaration.
176//
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000177ostream &CWriter::printType(std::ostream &Out, const Type *Ty, const string &NameSoFar,
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000178 bool IgnoreName, bool namedContext) {
Chris Lattner83c57752002-08-19 22:17:53 +0000179 if (Ty->isPrimitiveType())
180 switch (Ty->getPrimitiveID()) {
181 case Type::VoidTyID: return Out << "void " << NameSoFar;
182 case Type::BoolTyID: return Out << "bool " << NameSoFar;
183 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
184 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
185 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
186 case Type::ShortTyID: return Out << "short " << NameSoFar;
187 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
188 case Type::IntTyID: return Out << "int " << NameSoFar;
189 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
190 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
191 case Type::FloatTyID: return Out << "float " << NameSoFar;
192 case Type::DoubleTyID: return Out << "double " << NameSoFar;
193 default :
194 std::cerr << "Unknown primitive type: " << Ty << "\n";
195 abort();
196 }
197
198 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000199 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattner83c57752002-08-19 22:17:53 +0000200 map<const Type *, string>::iterator I = TypeNames.find(Ty);
201 if (I != TypeNames.end()) {
202 return Out << I->second << " " << NameSoFar;
203 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000204 }
Chris Lattner83c57752002-08-19 22:17:53 +0000205
Chris Lattner83c57752002-08-19 22:17:53 +0000206 switch (Ty->getPrimitiveID()) {
207 case Type::FunctionTyID: {
208 const FunctionType *MTy = cast<FunctionType>(Ty);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000209 std::stringstream FunctionInards;
210 FunctionInards << " (" << NameSoFar << ") (";
Chris Lattner83c57752002-08-19 22:17:53 +0000211 for (FunctionType::ParamTypes::const_iterator
212 I = MTy->getParamTypes().begin(),
213 E = MTy->getParamTypes().end(); I != E; ++I) {
214 if (I != MTy->getParamTypes().begin())
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000215 FunctionInards << ", ";
216 printType(FunctionInards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000217 }
218 if (MTy->isVarArg()) {
219 if (!MTy->getParamTypes().empty())
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000220 FunctionInards << ", ";
221 FunctionInards << "...";
Chris Lattner83c57752002-08-19 22:17:53 +0000222 }
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000223 FunctionInards << ")";
224 string tstr = FunctionInards.str();
225 printType(Out, MTy->getReturnType(), tstr);
226 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000227 }
228 case Type::StructTyID: {
229 const StructType *STy = cast<StructType>(Ty);
230 Out << NameSoFar + " {\n";
231 unsigned Idx = 0;
232 for (StructType::ElementTypes::const_iterator
233 I = STy->getElementTypes().begin(),
234 E = STy->getElementTypes().end(); I != E; ++I) {
235 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000236 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000237 Out << ";\n";
238 }
239 return Out << "}";
240 }
241
242 case Type::PointerTyID: {
243 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000244 std::string ptrName = "*" + NameSoFar;
245
246 // Do not need parens around "* NameSoFar" if NameSoFar consists only
247 // of zero or more '*' chars *and* this is not an unnamed pointer type
248 // such as the result type in a cast statement. Otherwise, enclose in ( ).
Nick Hildenbrandtc14ded42002-09-23 21:02:50 +0000249 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
250 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000251 ptrName = "(" + ptrName + ")"; //
252
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000253 return printType(Out, PTy->getElementType(), ptrName);
254 }Out <<"--";
Chris Lattner83c57752002-08-19 22:17:53 +0000255
256 case Type::ArrayTyID: {
257 const ArrayType *ATy = cast<ArrayType>(Ty);
258 unsigned NumElements = ATy->getNumElements();
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000259 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000260 NameSoFar + "[" + utostr(NumElements) + "]");
261 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000262
263 case Type::OpaqueTyID: {
264 static int Count = 0;
265 string TyName = "struct opaque_" + itostr(Count++);
266 assert(TypeNames.find(Ty) == TypeNames.end());
267 TypeNames[Ty] = TyName;
268 return Out << TyName << " " << NameSoFar;
269 }
Chris Lattner83c57752002-08-19 22:17:53 +0000270 default:
271 assert(0 && "Unhandled case in getTypeProps!");
272 abort();
273 }
274
275 return Out;
276}
277
Chris Lattner6d492922002-08-19 21:32:41 +0000278void CWriter::printConstantArray(ConstantArray *CPA) {
279
280 // As a special case, print the array as a string if it is an array of
281 // ubytes or an array of sbytes with positive values.
282 //
283 const Type *ETy = CPA->getType()->getElementType();
284 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
285
286 // Make sure the last character is a null char, as automatically added by C
287 if (CPA->getNumOperands() == 0 ||
288 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
289 isString = false;
290
291 if (isString) {
292 Out << "\"";
293 // Do not include the last character, which we know is null
294 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
295 unsigned char C = (ETy == Type::SByteTy) ?
296 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
297 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
298
299 if (isprint(C)) {
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000300 if (C == '"' || C == '\\')
301 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000302 else
303 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000304 } else {
305 switch (C) {
306 case '\n': Out << "\\n"; break;
307 case '\t': Out << "\\t"; break;
308 case '\r': Out << "\\r"; break;
309 case '\v': Out << "\\v"; break;
310 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000311 case '\"': Out << "\\\""; break;
312 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000313 default:
314 Out << "\\x";
315 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
316 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
317 break;
318 }
319 }
320 }
321 Out << "\"";
322 } else {
323 Out << "{";
324 if (CPA->getNumOperands()) {
325 Out << " ";
326 printConstant(cast<Constant>(CPA->getOperand(0)));
327 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
328 Out << ", ";
329 printConstant(cast<Constant>(CPA->getOperand(i)));
330 }
331 }
332 Out << " }";
333 }
334}
335
336
337// printConstant - The LLVM Constant to C Constant converter.
338void CWriter::printConstant(Constant *CPV) {
339 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
340 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000341 case Instruction::Cast:
342 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000343 printType(Out, CPV->getType());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000344 Out << ")";
345 printConstant(cast<Constant>(CPV->getOperand(0)));
346 Out << ")";
347 return;
348
349 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000350 Out << "(&(";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000351 printIndexingExpression(CPV->getOperand(0),
352 CPV->op_begin()+1, CPV->op_end());
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000353 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000354 return;
355 case Instruction::Add:
356 Out << "(";
357 printConstant(cast<Constant>(CPV->getOperand(0)));
358 Out << " + ";
359 printConstant(cast<Constant>(CPV->getOperand(1)));
360 Out << ")";
361 return;
362 case Instruction::Sub:
363 Out << "(";
364 printConstant(cast<Constant>(CPV->getOperand(0)));
365 Out << " - ";
366 printConstant(cast<Constant>(CPV->getOperand(1)));
367 Out << ")";
368 return;
369
Chris Lattner6d492922002-08-19 21:32:41 +0000370 default:
371 std::cerr << "CWriter Error: Unhandled constant expression: "
372 << CE << "\n";
373 abort();
374 }
375 }
376
377 switch (CPV->getType()->getPrimitiveID()) {
378 case Type::BoolTyID:
379 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
380 case Type::SByteTyID:
381 case Type::ShortTyID:
382 case Type::IntTyID:
383 Out << cast<ConstantSInt>(CPV)->getValue(); break;
384 case Type::LongTyID:
385 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
386
387 case Type::UByteTyID:
388 case Type::UShortTyID:
389 Out << cast<ConstantUInt>(CPV)->getValue(); break;
390 case Type::UIntTyID:
391 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
392 case Type::ULongTyID:
393 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
394
395 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000396 case Type::DoubleTyID: {
397 ConstantFP *FPC = cast<ConstantFP>(CPV);
398 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
399 if (I != FPConstantMap.end()) {
400 // Because of FP precision problems we must load from a stack allocated
401 // value that holds the value in hex.
402 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
403 << "*)&FloatConstant" << I->second << ")";
404 } else {
405 Out << FPC->getValue();
406 }
407 break;
408 }
Chris Lattner6d492922002-08-19 21:32:41 +0000409
410 case Type::ArrayTyID:
411 printConstantArray(cast<ConstantArray>(CPV));
412 break;
413
414 case Type::StructTyID: {
415 Out << "{";
416 if (CPV->getNumOperands()) {
417 Out << " ";
418 printConstant(cast<Constant>(CPV->getOperand(0)));
419 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
420 Out << ", ";
421 printConstant(cast<Constant>(CPV->getOperand(i)));
422 }
423 }
424 Out << " }";
425 break;
426 }
427
428 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000429 if (isa<ConstantPointerNull>(CPV)) {
Nick Hildenbrandtf0fca362002-10-28 19:54:06 +0000430 Out << "(NULL)";
Chris Lattner6d492922002-08-19 21:32:41 +0000431 break;
432 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
433 writeOperand(CPR->getValue());
434 break;
435 }
436 // FALL THROUGH
437 default:
438 std::cerr << "Unknown constant type: " << CPV << "\n";
439 abort();
440 }
441}
442
443void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000444 if (Instruction *I = dyn_cast<Instruction>(Operand))
445 if (isInlinableInst(*I)) {
446 // Should we inline this instruction to build a tree?
447 Out << "(";
448 visit(*I);
449 Out << ")";
450 return;
451 }
452
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000453 if (Operand->hasName()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000454 Out << getValueName(Operand);
455 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
456 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000457 } else {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000458 int Slot = Table->getValSlot(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000459 assert(Slot >= 0 && "Malformed LLVM!");
460 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
461 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000462}
463
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000464void CWriter::writeOperand(Value *Operand) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000465 if (isa<GlobalVariable>(Operand))
466 Out << "(&"; // Global variables are references as their addresses by llvm
467
468 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000469
470 if (isa<GlobalVariable>(Operand))
471 Out << ")";
472}
473
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000474// nameAllUsedStructureTypes - If there are structure types in the module that
475// are used but do not have names assigned to them in the symbol table yet then
476// we assign them names now.
477//
478bool CWriter::nameAllUsedStructureTypes(Module &M) {
479 // Get a set of types that are used by the program...
480 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
481
482 // Loop over the module symbol table, removing types from UT that are already
483 // named.
484 //
Chris Lattner6e6026b2002-11-20 18:36:02 +0000485 SymbolTable &MST = M.getSymbolTable();
486 if (MST.find(Type::TypeTy) != MST.end())
487 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
488 E = MST.type_end(Type::TypeTy); I != E; ++I)
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000489 UT.erase(cast<Type>(I->second));
490
491 // UT now contains types that are not named. Loop over it, naming structure
492 // types.
493 //
494 bool Changed = false;
495 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
496 I != E; ++I)
497 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000498 ((Value*)ST)->setName("unnamed", &MST);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000499 Changed = true;
500 }
501 return Changed;
502}
503
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000504static void generateAllocaDecl(ostream& Out)
505{
506 // On SunOS, we need to insert the alloca macro & proto for the builtin.
507 Out << "#ifdef sun\n"
508 << "extern void *__builtin_alloca(unsigned long);\n"
509 << "#define alloca(x) __builtin_alloca(x)\n"
510 << "#else\n"
511 << "#include <alloca.h>\n"
512 << "#endif\n\n";
513}
514
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000515void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000516 // Calculate which global values have names that will collide when we throw
517 // away type information.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000518 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattner78771c82002-05-17 04:55:35 +0000519 std::set<string> FoundNames;
520 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000521 if (I->hasName()) // If the global has a name...
522 if (FoundNames.count(I->getName())) // And the name is already used
523 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000524 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000525 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000526
527 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000528 if (I->hasName()) // If the global has a name...
529 if (FoundNames.count(I->getName())) // And the name is already used
530 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000531 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000532 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000533 }
534
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000535 // printing stdlib inclusion
Nick Hildenbrandt98360a12002-10-11 21:40:44 +0000536 //Out << "#include <stdlib.h>\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000537
Chris Lattner16c7bb22002-05-09 02:28:59 +0000538 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000539 Out << "/* Provide Declarations */\n";
540 generateAllocaDecl(Out);
541
542 // Provide a definition for null if one does not already exist,
543 // and for `bool' if not compiling with a C++ compiler.
544 Out << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000545 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000546
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000547 << "\n\n/* Support for floating point constants */\n"
548 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000549 << "typedef unsigned int ConstantFloatTy;\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000550
Chris Lattnera4d4a852002-08-19 21:48:40 +0000551 << "\n\n/* Global Declarations */\n";
552
553 // First output all the declarations for the program, because C requires
554 // Functions & globals to be declared before they are used.
555 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000556
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000557 // Loop over the symbol table, emitting all named constants...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000558 printSymbolTable(M->getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000559
Chris Lattnera4d4a852002-08-19 21:48:40 +0000560 // Global variable declarations...
561 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000562 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000563 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000564 if (I->hasExternalLinkage()) {
565 Out << "extern ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000566 printType(Out, I->getType()->getElementType(), getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000567 Out << ";\n";
568 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000569 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000570 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000571
Chris Lattnera4d4a852002-08-19 21:48:40 +0000572 // Function declarations
573 if (!M->empty()) {
574 Out << "\n/* Function Declarations */\n";
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000575 needsMalloc = true;
Chris Lattner4cda8352002-08-20 16:55:48 +0000576 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Nick Hildenbrandta1a64f82002-11-18 22:21:52 +0000577 // If the function is external and the name collides don't print it.
578 // Sometimes the bytecode likes to have multiple "declerations" for external functions
579 if (I->hasInternalLinkage() || !MangledGlobals.count(I)){
580 printFunctionSignature(I, true);
581 Out << ";\n";
582 }
Chris Lattner4cda8352002-08-20 16:55:48 +0000583 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000584 }
585
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000586 // Print Malloc prototype if needed
587 if (needsMalloc){
588 Out << "\n/* Malloc to make sun happy */\n";
589 Out << "extern void * malloc(size_t);\n\n";
590 }
591
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000592 // Output the global variable declerations
593 if (!M->gempty()) {
594 Out << "\n\n/* Global Variable Declerations */\n";
595 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
596 if (!I->isExternal()) {
597 Out << "extern ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000598 printType(Out, I->getType()->getElementType(), getValueName(I));
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000599
600 Out << ";\n";
601 }
602 }
603
604
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000605 // Output the global variable definitions and contents...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000606 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000607 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnere8e035b2002-10-16 20:08:47 +0000608 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
609 if (!I->isExternal()) {
610 if (I->hasInternalLinkage())
611 Out << "static ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000612 printType(Out, I->getType()->getElementType(), getValueName(I));
Chris Lattnera4d4a852002-08-19 21:48:40 +0000613
Chris Lattnera4d4a852002-08-19 21:48:40 +0000614 Out << " = " ;
615 writeOperand(I->getInitializer());
Chris Lattnere8e035b2002-10-16 20:08:47 +0000616 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000617 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000618 }
619
Chris Lattner16c7bb22002-05-09 02:28:59 +0000620 // Output all of the functions...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000621 if (!M->empty()) {
622 Out << "\n\n/* Function Bodies */\n";
623 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
624 printFunction(I);
625 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000626}
627
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000628
Chris Lattner2db41cd2002-09-20 15:12:13 +0000629/// printSymbolTable - Run through symbol table looking for type names. If a
630/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000631///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000632void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000633 // If there are no type names, exit early.
634 if (ST.find(Type::TypeTy) == ST.end())
635 return;
636
637 // We are only interested in the type plane of the symbol table...
638 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
639 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
640
Chris Lattner58d04d42002-09-20 15:18:30 +0000641 // Print out forward declarations for structure types before anything else!
642 Out << "/* Structure forward decls */\n";
643 for (; I != End; ++I)
644 if (const Type *STy = dyn_cast<StructType>(I->second)) {
645 string Name = "struct l_" + makeNameProper(I->first);
646 Out << Name << ";\n";
647 TypeNames.insert(std::make_pair(STy, Name));
648 }
649
650 Out << "\n";
651
652 // Now we can print out typedefs...
653 Out << "/* Typedefs */\n";
654 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
655 const Type *Ty = cast<Type>(I->second);
656 string Name = "l_" + makeNameProper(I->first);
657 Out << "typedef ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000658 printType(Out, Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000659 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000660 }
661
662 Out << "\n";
663
Chris Lattner2c601a72002-09-20 15:05:40 +0000664 // Keep track of which structures have been printed so far...
665 std::set<const StructType *> StructPrinted;
666
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000667 // Loop over all structures then push them into the stack so they are
668 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000669 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000670 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000671 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
672 if (const StructType *STy = dyn_cast<StructType>(I->second))
673 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000674}
675
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000676// Push the struct onto the stack and recursively push all structs
677// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000678void CWriter::printContainedStructs(const Type *Ty,
679 std::set<const StructType*> &StructPrinted){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000680 if (const StructType *STy = dyn_cast<StructType>(Ty)){
681 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000682 if (StructPrinted.count(STy) == 0) {
683 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000684 for (StructType::ElementTypes::const_iterator
685 I = STy->getElementTypes().begin(),
686 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000687 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000688 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000689 printContainedStructs(Ty1, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000690 }
691
Chris Lattner2c601a72002-09-20 15:05:40 +0000692 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000693 StructPrinted.insert(STy);
694 string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000695 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000696 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000697 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000698
Chris Lattner2c601a72002-09-20 15:05:40 +0000699 // If it is an array, check contained types and continue
700 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000701 const Type *Ty1 = ATy->getElementType();
702 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000703 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000704 }
705}
706
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000707
Chris Lattner4cda8352002-08-20 16:55:48 +0000708void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000709 // If the program provides it's own malloc prototype we don't need
710 // to include the general one.
711 if (getValueName(F) == "malloc")
712 needsMalloc = false;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000713 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000714 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000715 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000716
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000717 std::stringstream FunctionInards;
718
719 // Print out the name...
720 FunctionInards << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000721
Chris Lattner16c7bb22002-05-09 02:28:59 +0000722 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000723 if (!F->aempty()) {
Chris Lattner4cda8352002-08-20 16:55:48 +0000724 string ArgName;
725 if (F->abegin()->hasName() || !Prototype)
726 ArgName = getValueName(F->abegin());
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000727 printType(FunctionInards, F->afront().getType(), ArgName);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000728 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
729 I != E; ++I) {
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000730 FunctionInards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000731 if (I->hasName() || !Prototype)
732 ArgName = getValueName(I);
733 else
734 ArgName = "";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000735 printType(FunctionInards, I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000736 }
737 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000738 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000739 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000740 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000741 FT->getParamTypes().begin(),
742 E = FT->getParamTypes().end(); I != E; ++I) {
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000743 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
744 printType(FunctionInards, *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000745 }
746 }
747
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000748 // Finish printing arguments... if this is a vararg function, print the ...,
749 // unless there are no known types, in which case, we just emit ().
750 //
751 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000752 if (FT->getParamTypes().size()) FunctionInards << ", ";
753 FunctionInards << "..."; // Output varargs portion of signature!
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000754 }
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000755 FunctionInards << ")";
756 // Print out the return type and the entire signature for that matter
757 printType(Out, F->getReturnType(), FunctionInards.str());
758
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000759}
760
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000761
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000762void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000763 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000764
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000765 Table->incorporateFunction(F);
Chris Lattnerf34ee812002-05-09 03:12:34 +0000766
Chris Lattner4cda8352002-08-20 16:55:48 +0000767 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000768 Out << " {\n";
769
Chris Lattner497e19a2002-05-09 20:39:03 +0000770 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000771 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000772 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000773 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000774 printType(Out, (*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000775 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000776 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000777
778 Out << "\n";
779
780 // Scan the function for floating point constants. If any FP constant is used
781 // in the function, we want to redirect it here so that we do not depend on
782 // the precision of the printed form.
783 //
784 unsigned FPCounter = 0;
785 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
786 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
787 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
788 double Val = FPC->getValue();
789
790 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000791
792 if (FPC->getType() == Type::DoubleTy)
793 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
794 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
795 << "; /* " << Val << " */\n";
Chris Lattner9c1338b2002-11-07 22:12:53 +0000796 else if (FPC->getType() == Type::FloatTy) {
797 float fVal = Val;
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000798 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
Chris Lattner9c1338b2002-11-07 22:12:53 +0000799 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000800 << "; /* " << Val << " */\n";
Chris Lattner9c1338b2002-11-07 22:12:53 +0000801 } else
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000802 assert(0 && "Unknown float type!");
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000803 }
804
805 Out << "\n";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000806
807 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000808 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
809 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000810
811 // Don't print the label for the basic block if there are no uses, or if the
812 // only terminator use is the precessor basic block's terminator. We have
813 // to scan the use list because PHI nodes use basic blocks too but do not
814 // require a label to be generated.
815 //
816 bool NeedsLabel = false;
817 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
818 UI != UE; ++UI)
819 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
820 if (TI != Prev->getTerminator()) {
821 NeedsLabel = true;
822 break;
823 }
824
825 if (NeedsLabel) Out << getValueName(BB) << ":\n";
826
827 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000828 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000829 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000830 if (II->getType() != Type::VoidTy)
831 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000832 else
833 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000834 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000835 Out << ";\n";
836 }
837 }
838
839 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000840 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000841 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000842
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000843 Out << "}\n\n";
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000844 Table->purgeFunction();
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000845 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000846}
847
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000848// Specific Instruction type classes... note that all of the casts are
849// neccesary because we use the instruction classes as opaque types...
850//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000851void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000852 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000853 if (I.getNumOperands() == 0 &&
854 &*--I.getParent()->getParent()->end() == I.getParent() &&
855 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000856 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000857 }
Chris Lattner44408262002-05-09 03:50:42 +0000858
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000859 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000860 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000861 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000862 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000863 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000864 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000865}
866
Chris Lattnera9f5e052003-04-22 20:19:52 +0000867void CWriter::visitSwitchInst(SwitchInst &SI) {
868 Out << " switch (";
869 writeOperand(SI.getOperand(0));
870 Out << ") {\n default: goto ";
871 writeOperand(SI.getDefaultDest());
872 Out << ";\n";
873 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
874 Out << " case ";
875 writeOperand(SI.getOperand(i));
876 Out << ":\n";
877 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
878 printBranchToBlock(SI.getParent(), Succ, 2);
879 if (Succ == SI.getParent()->getNext())
880 Out << " break;\n";
881 }
882 Out << " }\n";
883}
884
885
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000886static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
887 // If PHI nodes need copies, we need the copy code...
888 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000889 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000890 return true;
891
892 // Otherwise we don't need the code.
893 return false;
894}
895
896void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
897 unsigned Indent) {
898 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner2ee82e02003-04-23 16:36:11 +0000899 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000900 // now we have to do the printing
901 Out << string(Indent, ' ');
902 outputLValue(PN);
903 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
904 Out << "; /* for PHI node */\n";
905 }
906
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000907 if (CurBB->getNext() != Succ) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000908 Out << string(Indent, ' ') << " goto ";
909 writeOperand(Succ);
910 Out << ";\n";
911 }
912}
913
914// Brach instruction printing - Avoid printing out a brach to a basic block that
915// immediately succeeds the current one.
916//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000917void CWriter::visitBranchInst(BranchInst &I) {
918 if (I.isConditional()) {
919 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000920 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000921 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000922 Out << ") {\n";
923
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000924 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000925
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000926 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000927 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000928 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000929 }
930 } else {
931 // First goto not neccesary, assume second one is...
932 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000933 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000934 Out << ") {\n";
935
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000936 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000937 }
938
939 Out << " }\n";
940 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000941 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000942 }
943 Out << "\n";
944}
945
946
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000947void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000948 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +0000949 assert(!isa<PointerType>(I.getType()));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000950
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000951 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000952
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000953 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000954 case Instruction::Add: Out << " + "; break;
955 case Instruction::Sub: Out << " - "; break;
956 case Instruction::Mul: Out << "*"; break;
957 case Instruction::Div: Out << "/"; break;
958 case Instruction::Rem: Out << "%"; break;
959 case Instruction::And: Out << " & "; break;
960 case Instruction::Or: Out << " | "; break;
961 case Instruction::Xor: Out << " ^ "; break;
962 case Instruction::SetEQ: Out << " == "; break;
963 case Instruction::SetNE: Out << " != "; break;
964 case Instruction::SetLE: Out << " <= "; break;
965 case Instruction::SetGE: Out << " >= "; break;
966 case Instruction::SetLT: Out << " < "; break;
967 case Instruction::SetGT: Out << " > "; break;
968 case Instruction::Shl : Out << " << "; break;
969 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000970 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000971 }
972
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000973 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000974}
975
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000976void CWriter::visitCastInst(CastInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000977 Out << "(";
Chris Lattnerf5612b762003-04-23 19:09:22 +0000978 printType(Out, I.getType(), string(""),/*ignoreName*/false,
979 /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000980 Out << ")";
Chris Lattnerf5612b762003-04-23 19:09:22 +0000981 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
982 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
983 // Avoid "cast to pointer from integer of different size" warnings
984 Out << "(long)";
985 }
986
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000987 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000988}
989
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000990void CWriter::visitCallInst(CallInst &I) {
991 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000992 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
993 const Type *RetTy = FTy->getReturnType();
994
Chris Lattnerfabc8802002-08-26 20:50:09 +0000995 writeOperand(I.getOperand(0));
996 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000997
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000998 if (I.getNumOperands() > 1) {
999 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001000
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001001 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001002 Out << ", ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001003 writeOperand(I.getOperand(op));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001004 }
1005 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001006 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001007}
1008
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001009void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001010 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001011 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001012 Out << ")malloc(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001013 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001014 Out << ")";
1015
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001016 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001017 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001018 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001019 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001020 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001021}
1022
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001023void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001024 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001025 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001026 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001027 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001028 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001029 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001030 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001031 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001032 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001033 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001034}
1035
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001036void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001037 Out << "free(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001038 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001039 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001040}
1041
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001042void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1043 User::op_iterator E) {
1044 bool HasImplicitAddress = false;
1045 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1046 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1047 HasImplicitAddress = true;
1048 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1049 HasImplicitAddress = true;
1050 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001051 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001052
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001053 if (I == E) {
1054 if (!HasImplicitAddress)
1055 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001056
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001057 writeOperandInternal(Ptr);
1058 return;
1059 }
1060
1061 const Constant *CI = dyn_cast<Constant>(I->get());
1062 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1063 Out << "(&";
1064
1065 writeOperandInternal(Ptr);
1066
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001067 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001068 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001069 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1070 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001071
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001072 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1073 "Can only have implicit address with direct accessing");
1074
1075 if (HasImplicitAddress) {
1076 ++I;
1077 } else if (CI && CI->isNullValue() && I+1 != E) {
1078 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001079 if ((*(I+1))->getType() == Type::UByteTy) {
1080 Out << (HasImplicitAddress ? "." : "->");
1081 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1082 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001083 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001084 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001085
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001086 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001087 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001088 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001089 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001090 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001091 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001092 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001093 }
1094}
1095
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001096void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001097 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001098 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001099}
1100
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001101void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001102 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001103 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001104 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001105 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001106}
1107
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001108void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001109 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001110 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001111}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001112
1113//===----------------------------------------------------------------------===//
1114// External Interface declaration
1115//===----------------------------------------------------------------------===//
1116
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001117Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }