blob: fcfda5d15a0d2a7b20059a15761822b8b6def370 [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"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000010#include "llvm/iMemory.h"
11#include "llvm/iTerminators.h"
12#include "llvm/iPHINode.h"
13#include "llvm/iOther.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000014#include "llvm/iOperators.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000015#include "llvm/Pass.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000016#include "llvm/SymbolTable.h"
Chris Lattner3af3ba82002-05-09 21:31:18 +000017#include "llvm/SlotCalculator.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000018#include "llvm/Analysis/FindUsedTypes.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000019#include "llvm/Analysis/ConstantsScanner.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000020#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000021#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000022#include "Support/StringExtras.h"
23#include "Support/STLExtras.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000024#include <algorithm>
Chris Lattner78771c82002-05-17 04:55:35 +000025#include <set>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000026#include <sstream>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000027using std::string;
28using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000029using std::ostream;
30
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000031
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000032namespace {
Chris Lattner0e9f93e2002-08-31 00:29:16 +000033 class CWriter : public Pass, public InstVisitor<CWriter> {
34 ostream &Out;
35 SlotCalculator *Table;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000036 const Module *TheModule;
37 map<const Type *, string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +000038 std::set<const Value*> MangledGlobals;
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000039 bool needsMalloc;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000040
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000041 map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000042 public:
Chris Lattner0e9f93e2002-08-31 00:29:16 +000043 CWriter(ostream &o) : Out(o) {}
44
45 void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.setPreservesAll();
47 AU.addRequired<FindUsedTypes>();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000048 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000049
50 virtual bool run(Module &M) {
51 // Initialize
52 Table = new SlotCalculator(&M, false);
53 TheModule = &M;
54
55 // Ensure that all structure types have names...
56 bool Changed = nameAllUsedStructureTypes(M);
57
58 // Run...
59 printModule(&M);
60
61 // Free memory...
62 delete Table;
63 TypeNames.clear();
64 MangledGlobals.clear();
65 return false;
66 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000067
Nick Hildenbrandt98502372002-11-18 20:55:50 +000068 ostream &printType(std::ostream &Out, const Type *Ty, const string &VariableName = "",
Vikram S. Adve969c4ad2002-08-25 20:00:08 +000069 bool IgnoreName = false, bool namedContext = true);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000070
Chris Lattnerbb03efd2002-06-25 15:57:03 +000071 void writeOperand(Value *Operand);
72 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000073
74 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000075
Chris Lattner4fbf26d2002-05-09 20:53:56 +000076 private :
Chris Lattner0e9f93e2002-08-31 00:29:16 +000077 bool nameAllUsedStructureTypes(Module &M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000078 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 void printSymbolTable(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +000080 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000081 void printGlobal(const GlobalVariable *GV);
Chris Lattner4cda8352002-08-20 16:55:48 +000082 void printFunctionSignature(const Function *F, bool Prototype);
83
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000084 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000085
Chris Lattner6d492922002-08-19 21:32:41 +000086 void printConstant(Constant *CPV);
87 void printConstantArray(ConstantArray *CPA);
88
Chris Lattnerd0c668c2002-05-09 21:18:38 +000089 // isInlinableInst - Attempt to inline instructions into their uses to build
90 // trees as much as possible. To do this, we have to consistently decide
91 // what is acceptable to inline, so that variable declarations don't get
92 // printed and an extra copy of the expr is not emitted.
93 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +000094 static bool isInlinableInst(const Instruction &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +000095 // Must be an expression, must be used exactly once. If it is dead, we
96 // emit it inline where it would go.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000097 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
Nick Hildenbrandt2cf2cbc2002-11-06 20:07:54 +000098 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
99 isa<LoadInst>(I)) // Don't inline a load across a store!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000100 return false;
101
102 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000103 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000104 }
105
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000106 // Instruction visitation functions
107 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000108
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000109 void visitReturnInst(ReturnInst &I);
110 void visitBranchInst(BranchInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000111
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000112 void visitPHINode(PHINode &I) {}
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000113 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000114
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000115 void visitCastInst (CastInst &I);
116 void visitCallInst (CallInst &I);
117 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000118
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000119 void visitMallocInst(MallocInst &I);
120 void visitAllocaInst(AllocaInst &I);
121 void visitFreeInst (FreeInst &I);
122 void visitLoadInst (LoadInst &I);
123 void visitStoreInst (StoreInst &I);
124 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000125
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000126 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000127 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000128 abort();
129 }
130
131 void outputLValue(Instruction *I) {
132 Out << " " << getValueName(I) << " = ";
133 }
134 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
135 unsigned Indent);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000136 void printIndexingExpression(Value *Ptr, User::op_iterator I,
137 User::op_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000138 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000139}
140
Chris Lattner2f499022002-05-09 04:21:21 +0000141// We dont want identifier names with ., space, - in them.
142// So we replace them with _
143static string makeNameProper(string x) {
144 string tmp;
145 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
146 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000147 case '.': tmp += "d_"; break;
148 case ' ': tmp += "s_"; break;
149 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000150 default: tmp += *sI;
151 }
152
153 return tmp;
154}
155
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000156string CWriter::getValueName(const Value *V) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000157 if (V->hasName()) { // Print out the label if it exists...
158 if (isa<GlobalValue>(V) && // Do not mangle globals...
Nick Hildenbrandta1a64f82002-11-18 22:21:52 +0000159 cast<GlobalValue>(V)->hasExternalLinkage())// && // Unless it's internal or
160 //!MangledGlobals.count(V)) // Unless the name would collide if we don't
Chris Lattner2f499022002-05-09 04:21:21 +0000161 return makeNameProper(V->getName());
162
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000163 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
164 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000165 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000166
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000167 int Slot = Table->getValSlot(V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000168 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000169 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000170}
171
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000172// A pointer type should not use parens around *'s alone, e.g., (**)
173inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
174 return (NameSoFar.find_last_not_of('*') != std::string::npos);
175}
176
Chris Lattner83c57752002-08-19 22:17:53 +0000177// Pass the Type* and the variable name and this prints out the variable
178// declaration.
179//
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000180ostream &CWriter::printType(std::ostream &Out, const Type *Ty, const string &NameSoFar,
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000181 bool IgnoreName, bool namedContext) {
Chris Lattner83c57752002-08-19 22:17:53 +0000182 if (Ty->isPrimitiveType())
183 switch (Ty->getPrimitiveID()) {
184 case Type::VoidTyID: return Out << "void " << NameSoFar;
185 case Type::BoolTyID: return Out << "bool " << NameSoFar;
186 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
187 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
188 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
189 case Type::ShortTyID: return Out << "short " << NameSoFar;
190 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
191 case Type::IntTyID: return Out << "int " << NameSoFar;
192 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
193 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
194 case Type::FloatTyID: return Out << "float " << NameSoFar;
195 case Type::DoubleTyID: return Out << "double " << NameSoFar;
196 default :
197 std::cerr << "Unknown primitive type: " << Ty << "\n";
198 abort();
199 }
200
201 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000202 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattner83c57752002-08-19 22:17:53 +0000203 map<const Type *, string>::iterator I = TypeNames.find(Ty);
204 if (I != TypeNames.end()) {
205 return Out << I->second << " " << NameSoFar;
206 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000207 }
Chris Lattner83c57752002-08-19 22:17:53 +0000208
Chris Lattner83c57752002-08-19 22:17:53 +0000209 switch (Ty->getPrimitiveID()) {
210 case Type::FunctionTyID: {
211 const FunctionType *MTy = cast<FunctionType>(Ty);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000212 std::stringstream FunctionInards;
213 FunctionInards << " (" << NameSoFar << ") (";
Chris Lattner83c57752002-08-19 22:17:53 +0000214 for (FunctionType::ParamTypes::const_iterator
215 I = MTy->getParamTypes().begin(),
216 E = MTy->getParamTypes().end(); I != E; ++I) {
217 if (I != MTy->getParamTypes().begin())
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000218 FunctionInards << ", ";
219 printType(FunctionInards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000220 }
221 if (MTy->isVarArg()) {
222 if (!MTy->getParamTypes().empty())
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000223 FunctionInards << ", ";
224 FunctionInards << "...";
Chris Lattner83c57752002-08-19 22:17:53 +0000225 }
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000226 FunctionInards << ")";
227 string tstr = FunctionInards.str();
228 printType(Out, MTy->getReturnType(), tstr);
229 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000230 }
231 case Type::StructTyID: {
232 const StructType *STy = cast<StructType>(Ty);
233 Out << NameSoFar + " {\n";
234 unsigned Idx = 0;
235 for (StructType::ElementTypes::const_iterator
236 I = STy->getElementTypes().begin(),
237 E = STy->getElementTypes().end(); I != E; ++I) {
238 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000239 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000240 Out << ";\n";
241 }
242 return Out << "}";
243 }
244
245 case Type::PointerTyID: {
246 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000247 std::string ptrName = "*" + NameSoFar;
248
249 // Do not need parens around "* NameSoFar" if NameSoFar consists only
250 // of zero or more '*' chars *and* this is not an unnamed pointer type
251 // such as the result type in a cast statement. Otherwise, enclose in ( ).
Nick Hildenbrandtc14ded42002-09-23 21:02:50 +0000252 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
253 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000254 ptrName = "(" + ptrName + ")"; //
255
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000256 return printType(Out, PTy->getElementType(), ptrName);
257 }Out <<"--";
Chris Lattner83c57752002-08-19 22:17:53 +0000258
259 case Type::ArrayTyID: {
260 const ArrayType *ATy = cast<ArrayType>(Ty);
261 unsigned NumElements = ATy->getNumElements();
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000262 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000263 NameSoFar + "[" + utostr(NumElements) + "]");
264 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000265
266 case Type::OpaqueTyID: {
267 static int Count = 0;
268 string TyName = "struct opaque_" + itostr(Count++);
269 assert(TypeNames.find(Ty) == TypeNames.end());
270 TypeNames[Ty] = TyName;
271 return Out << TyName << " " << NameSoFar;
272 }
Chris Lattner83c57752002-08-19 22:17:53 +0000273 default:
274 assert(0 && "Unhandled case in getTypeProps!");
275 abort();
276 }
277
278 return Out;
279}
280
Chris Lattner6d492922002-08-19 21:32:41 +0000281void CWriter::printConstantArray(ConstantArray *CPA) {
282
283 // As a special case, print the array as a string if it is an array of
284 // ubytes or an array of sbytes with positive values.
285 //
286 const Type *ETy = CPA->getType()->getElementType();
287 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
288
289 // Make sure the last character is a null char, as automatically added by C
290 if (CPA->getNumOperands() == 0 ||
291 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
292 isString = false;
293
294 if (isString) {
295 Out << "\"";
296 // Do not include the last character, which we know is null
297 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
298 unsigned char C = (ETy == Type::SByteTy) ?
299 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
300 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
301
302 if (isprint(C)) {
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000303 if (C == '"' || C == '\\')
304 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000305 else
306 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000307 } else {
308 switch (C) {
309 case '\n': Out << "\\n"; break;
310 case '\t': Out << "\\t"; break;
311 case '\r': Out << "\\r"; break;
312 case '\v': Out << "\\v"; break;
313 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000314 case '\"': Out << "\\\""; break;
315 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000316 default:
317 Out << "\\x";
318 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
319 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
320 break;
321 }
322 }
323 }
324 Out << "\"";
325 } else {
326 Out << "{";
327 if (CPA->getNumOperands()) {
328 Out << " ";
329 printConstant(cast<Constant>(CPA->getOperand(0)));
330 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
331 Out << ", ";
332 printConstant(cast<Constant>(CPA->getOperand(i)));
333 }
334 }
335 Out << " }";
336 }
337}
338
339
340// printConstant - The LLVM Constant to C Constant converter.
341void CWriter::printConstant(Constant *CPV) {
342 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
343 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000344 case Instruction::Cast:
345 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000346 printType(Out, CPV->getType());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000347 Out << ")";
348 printConstant(cast<Constant>(CPV->getOperand(0)));
349 Out << ")";
350 return;
351
352 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000353 Out << "(&(";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000354 printIndexingExpression(CPV->getOperand(0),
355 CPV->op_begin()+1, CPV->op_end());
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000356 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000357 return;
358 case Instruction::Add:
359 Out << "(";
360 printConstant(cast<Constant>(CPV->getOperand(0)));
361 Out << " + ";
362 printConstant(cast<Constant>(CPV->getOperand(1)));
363 Out << ")";
364 return;
365 case Instruction::Sub:
366 Out << "(";
367 printConstant(cast<Constant>(CPV->getOperand(0)));
368 Out << " - ";
369 printConstant(cast<Constant>(CPV->getOperand(1)));
370 Out << ")";
371 return;
372
Chris Lattner6d492922002-08-19 21:32:41 +0000373 default:
374 std::cerr << "CWriter Error: Unhandled constant expression: "
375 << CE << "\n";
376 abort();
377 }
378 }
379
380 switch (CPV->getType()->getPrimitiveID()) {
381 case Type::BoolTyID:
382 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
383 case Type::SByteTyID:
384 case Type::ShortTyID:
385 case Type::IntTyID:
386 Out << cast<ConstantSInt>(CPV)->getValue(); break;
387 case Type::LongTyID:
388 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
389
390 case Type::UByteTyID:
391 case Type::UShortTyID:
392 Out << cast<ConstantUInt>(CPV)->getValue(); break;
393 case Type::UIntTyID:
394 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
395 case Type::ULongTyID:
396 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
397
398 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000399 case Type::DoubleTyID: {
400 ConstantFP *FPC = cast<ConstantFP>(CPV);
401 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
402 if (I != FPConstantMap.end()) {
403 // Because of FP precision problems we must load from a stack allocated
404 // value that holds the value in hex.
405 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
406 << "*)&FloatConstant" << I->second << ")";
407 } else {
408 Out << FPC->getValue();
409 }
410 break;
411 }
Chris Lattner6d492922002-08-19 21:32:41 +0000412
413 case Type::ArrayTyID:
414 printConstantArray(cast<ConstantArray>(CPV));
415 break;
416
417 case Type::StructTyID: {
418 Out << "{";
419 if (CPV->getNumOperands()) {
420 Out << " ";
421 printConstant(cast<Constant>(CPV->getOperand(0)));
422 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
423 Out << ", ";
424 printConstant(cast<Constant>(CPV->getOperand(i)));
425 }
426 }
427 Out << " }";
428 break;
429 }
430
431 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000432 if (isa<ConstantPointerNull>(CPV)) {
Nick Hildenbrandtf0fca362002-10-28 19:54:06 +0000433 Out << "(NULL)";
Chris Lattner6d492922002-08-19 21:32:41 +0000434 break;
435 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
436 writeOperand(CPR->getValue());
437 break;
438 }
439 // FALL THROUGH
440 default:
441 std::cerr << "Unknown constant type: " << CPV << "\n";
442 abort();
443 }
444}
445
446void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000447 if (Instruction *I = dyn_cast<Instruction>(Operand))
448 if (isInlinableInst(*I)) {
449 // Should we inline this instruction to build a tree?
450 Out << "(";
451 visit(*I);
452 Out << ")";
453 return;
454 }
455
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000456 if (Operand->hasName()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000457 Out << getValueName(Operand);
458 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
459 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000460 } else {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000461 int Slot = Table->getValSlot(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000462 assert(Slot >= 0 && "Malformed LLVM!");
463 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
464 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000465}
466
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000467void CWriter::writeOperand(Value *Operand) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000468 if (isa<GlobalVariable>(Operand))
469 Out << "(&"; // Global variables are references as their addresses by llvm
470
471 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000472
473 if (isa<GlobalVariable>(Operand))
474 Out << ")";
475}
476
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000477// nameAllUsedStructureTypes - If there are structure types in the module that
478// are used but do not have names assigned to them in the symbol table yet then
479// we assign them names now.
480//
481bool CWriter::nameAllUsedStructureTypes(Module &M) {
482 // Get a set of types that are used by the program...
483 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
484
485 // Loop over the module symbol table, removing types from UT that are already
486 // named.
487 //
488 SymbolTable *MST = M.getSymbolTableSure();
489 if (MST->find(Type::TypeTy) != MST->end())
490 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
491 E = MST->type_end(Type::TypeTy); I != E; ++I)
492 UT.erase(cast<Type>(I->second));
493
494 // UT now contains types that are not named. Loop over it, naming structure
495 // types.
496 //
497 bool Changed = false;
498 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
499 I != E; ++I)
500 if (const StructType *ST = dyn_cast<StructType>(*I)) {
501 ((Value*)ST)->setName("unnamed", MST);
502 Changed = true;
503 }
504 return Changed;
505}
506
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000507void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000508 // Calculate which global values have names that will collide when we throw
509 // away type information.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000510 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattner78771c82002-05-17 04:55:35 +0000511 std::set<string> FoundNames;
512 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000513 if (I->hasName()) // If the global has a name...
514 if (FoundNames.count(I->getName())) // And the name is already used
515 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000516 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000517 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000518
519 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000520 if (I->hasName()) // If the global has a name...
521 if (FoundNames.count(I->getName())) // And the name is already used
522 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000523 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000524 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000525 }
526
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000527 // printing stdlib inclusion
Nick Hildenbrandt98360a12002-10-11 21:40:44 +0000528 //Out << "#include <stdlib.h>\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000529
Chris Lattner16c7bb22002-05-09 02:28:59 +0000530 // get declaration for alloca
531 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000532 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000533
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000534 // Provide a definition for null if one does not already exist,
535 // and for `bool' if not compiling with a C++ compiler.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000536 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000537 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000538
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000539 << "\n\n/* Support for floating point constants */\n"
540 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000541 << "typedef unsigned int ConstantFloatTy;\n"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000542
Chris Lattnera4d4a852002-08-19 21:48:40 +0000543 << "\n\n/* Global Declarations */\n";
544
545 // First output all the declarations for the program, because C requires
546 // Functions & globals to be declared before they are used.
547 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000548
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000549 // Loop over the symbol table, emitting all named constants...
550 if (M->hasSymbolTable())
551 printSymbolTable(*M->getSymbolTable());
552
Chris Lattnera4d4a852002-08-19 21:48:40 +0000553 // Global variable declarations...
554 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000555 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000556 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000557 if (I->hasExternalLinkage()) {
558 Out << "extern ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000559 printType(Out, I->getType()->getElementType(), getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000560 Out << ";\n";
561 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000562 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000563 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000564
Chris Lattnera4d4a852002-08-19 21:48:40 +0000565 // Function declarations
566 if (!M->empty()) {
567 Out << "\n/* Function Declarations */\n";
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000568 needsMalloc = true;
Chris Lattner4cda8352002-08-20 16:55:48 +0000569 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Nick Hildenbrandta1a64f82002-11-18 22:21:52 +0000570 // If the function is external and the name collides don't print it.
571 // Sometimes the bytecode likes to have multiple "declerations" for external functions
572 if (I->hasInternalLinkage() || !MangledGlobals.count(I)){
573 printFunctionSignature(I, true);
574 Out << ";\n";
575 }
Chris Lattner4cda8352002-08-20 16:55:48 +0000576 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000577 }
578
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000579 // Print Malloc prototype if needed
580 if (needsMalloc){
581 Out << "\n/* Malloc to make sun happy */\n";
582 Out << "extern void * malloc(size_t);\n\n";
583 }
584
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000585 // Output the global variable declerations
586 if (!M->gempty()) {
587 Out << "\n\n/* Global Variable Declerations */\n";
588 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
589 if (!I->isExternal()) {
590 Out << "extern ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000591 printType(Out, I->getType()->getElementType(), getValueName(I));
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000592
593 Out << ";\n";
594 }
595 }
596
597
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000598 // Output the global variable definitions and contents...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000599 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000600 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnere8e035b2002-10-16 20:08:47 +0000601 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
602 if (!I->isExternal()) {
603 if (I->hasInternalLinkage())
604 Out << "static ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000605 printType(Out, I->getType()->getElementType(), getValueName(I));
Chris Lattnera4d4a852002-08-19 21:48:40 +0000606
Chris Lattnera4d4a852002-08-19 21:48:40 +0000607 Out << " = " ;
608 writeOperand(I->getInitializer());
Chris Lattnere8e035b2002-10-16 20:08:47 +0000609 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000610 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000611 }
612
Chris Lattner16c7bb22002-05-09 02:28:59 +0000613 // Output all of the functions...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000614 if (!M->empty()) {
615 Out << "\n\n/* Function Bodies */\n";
616 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
617 printFunction(I);
618 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000619}
620
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000621
Chris Lattner2db41cd2002-09-20 15:12:13 +0000622/// printSymbolTable - Run through symbol table looking for type names. If a
623/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000624///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000625void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000626 // If there are no type names, exit early.
627 if (ST.find(Type::TypeTy) == ST.end())
628 return;
629
630 // We are only interested in the type plane of the symbol table...
631 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
632 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
633
Chris Lattner58d04d42002-09-20 15:18:30 +0000634 // Print out forward declarations for structure types before anything else!
635 Out << "/* Structure forward decls */\n";
636 for (; I != End; ++I)
637 if (const Type *STy = dyn_cast<StructType>(I->second)) {
638 string Name = "struct l_" + makeNameProper(I->first);
639 Out << Name << ";\n";
640 TypeNames.insert(std::make_pair(STy, Name));
641 }
642
643 Out << "\n";
644
645 // Now we can print out typedefs...
646 Out << "/* Typedefs */\n";
647 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
648 const Type *Ty = cast<Type>(I->second);
649 string Name = "l_" + makeNameProper(I->first);
650 Out << "typedef ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000651 printType(Out, Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000652 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000653 }
654
655 Out << "\n";
656
Chris Lattner2c601a72002-09-20 15:05:40 +0000657 // Keep track of which structures have been printed so far...
658 std::set<const StructType *> StructPrinted;
659
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000660 // Loop over all structures then push them into the stack so they are
661 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000662 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000663 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000664 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
665 if (const StructType *STy = dyn_cast<StructType>(I->second))
666 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000667}
668
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000669// Push the struct onto the stack and recursively push all structs
670// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000671void CWriter::printContainedStructs(const Type *Ty,
672 std::set<const StructType*> &StructPrinted){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000673 if (const StructType *STy = dyn_cast<StructType>(Ty)){
674 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000675 if (StructPrinted.count(STy) == 0) {
676 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000677 for (StructType::ElementTypes::const_iterator
678 I = STy->getElementTypes().begin(),
679 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000680 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000681 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000682 printContainedStructs(Ty1, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000683 }
684
Chris Lattner2c601a72002-09-20 15:05:40 +0000685 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000686 StructPrinted.insert(STy);
687 string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000688 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000689 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000690 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000691
Chris Lattner2c601a72002-09-20 15:05:40 +0000692 // If it is an array, check contained types and continue
693 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000694 const Type *Ty1 = ATy->getElementType();
695 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000696 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000697 }
698}
699
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000700
Chris Lattner4cda8352002-08-20 16:55:48 +0000701void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000702 // If the program provides it's own malloc prototype we don't need
703 // to include the general one.
704 if (getValueName(F) == "malloc")
705 needsMalloc = false;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000706 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000707 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000708 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000709
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000710 std::stringstream FunctionInards;
711
712 // Print out the name...
713 FunctionInards << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000714
Chris Lattner16c7bb22002-05-09 02:28:59 +0000715 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000716 if (!F->aempty()) {
Chris Lattner4cda8352002-08-20 16:55:48 +0000717 string ArgName;
718 if (F->abegin()->hasName() || !Prototype)
719 ArgName = getValueName(F->abegin());
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000720 printType(FunctionInards, F->afront().getType(), ArgName);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000721 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
722 I != E; ++I) {
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000723 FunctionInards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000724 if (I->hasName() || !Prototype)
725 ArgName = getValueName(I);
726 else
727 ArgName = "";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000728 printType(FunctionInards, I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000729 }
730 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000731 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000732 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000733 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000734 FT->getParamTypes().begin(),
735 E = FT->getParamTypes().end(); I != E; ++I) {
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000736 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
737 printType(FunctionInards, *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000738 }
739 }
740
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000741 // Finish printing arguments... if this is a vararg function, print the ...,
742 // unless there are no known types, in which case, we just emit ().
743 //
744 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000745 if (FT->getParamTypes().size()) FunctionInards << ", ";
746 FunctionInards << "..."; // Output varargs portion of signature!
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000747 }
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000748 FunctionInards << ")";
749 // Print out the return type and the entire signature for that matter
750 printType(Out, F->getReturnType(), FunctionInards.str());
751
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000752}
753
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000754
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000755void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000756 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000757
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000758 Table->incorporateFunction(F);
Chris Lattnerf34ee812002-05-09 03:12:34 +0000759
Chris Lattner4cda8352002-08-20 16:55:48 +0000760 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000761 Out << " {\n";
762
Chris Lattner497e19a2002-05-09 20:39:03 +0000763 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000764 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000765 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000766 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000767 printType(Out, (*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000768 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000769 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000770
771 Out << "\n";
772
773 // Scan the function for floating point constants. If any FP constant is used
774 // in the function, we want to redirect it here so that we do not depend on
775 // the precision of the printed form.
776 //
777 unsigned FPCounter = 0;
778 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
779 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
780 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
781 double Val = FPC->getValue();
782
783 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000784
785 if (FPC->getType() == Type::DoubleTy)
786 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
787 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
788 << "; /* " << Val << " */\n";
Chris Lattner9c1338b2002-11-07 22:12:53 +0000789 else if (FPC->getType() == Type::FloatTy) {
790 float fVal = Val;
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000791 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
Chris Lattner9c1338b2002-11-07 22:12:53 +0000792 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000793 << "; /* " << Val << " */\n";
Chris Lattner9c1338b2002-11-07 22:12:53 +0000794 } else
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000795 assert(0 && "Unknown float type!");
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000796 }
797
798 Out << "\n";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000799
800 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000801 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
802 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000803
804 // Don't print the label for the basic block if there are no uses, or if the
805 // only terminator use is the precessor basic block's terminator. We have
806 // to scan the use list because PHI nodes use basic blocks too but do not
807 // require a label to be generated.
808 //
809 bool NeedsLabel = false;
810 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
811 UI != UE; ++UI)
812 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
813 if (TI != Prev->getTerminator()) {
814 NeedsLabel = true;
815 break;
816 }
817
818 if (NeedsLabel) Out << getValueName(BB) << ":\n";
819
820 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000821 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000822 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000823 if (II->getType() != Type::VoidTy)
824 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000825 else
826 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000827 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000828 Out << ";\n";
829 }
830 }
831
832 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000833 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000834 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000835
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000836 Out << "}\n\n";
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000837 Table->purgeFunction();
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000838 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000839}
840
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000841// Specific Instruction type classes... note that all of the casts are
842// neccesary because we use the instruction classes as opaque types...
843//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000844void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000845 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000846 if (I.getNumOperands() == 0 &&
847 &*--I.getParent()->getParent()->end() == I.getParent() &&
848 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000849 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000850 }
Chris Lattner44408262002-05-09 03:50:42 +0000851
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000852 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000853 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000854 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000855 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000856 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000857 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000858}
859
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000860static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
861 // If PHI nodes need copies, we need the copy code...
862 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000863 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000864 return true;
865
866 // Otherwise we don't need the code.
867 return false;
868}
869
870void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
871 unsigned Indent) {
872 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000873 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000874 // now we have to do the printing
875 Out << string(Indent, ' ');
876 outputLValue(PN);
877 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
878 Out << "; /* for PHI node */\n";
879 }
880
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000881 if (CurBB->getNext() != Succ) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000882 Out << string(Indent, ' ') << " goto ";
883 writeOperand(Succ);
884 Out << ";\n";
885 }
886}
887
888// Brach instruction printing - Avoid printing out a brach to a basic block that
889// immediately succeeds the current one.
890//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000891void CWriter::visitBranchInst(BranchInst &I) {
892 if (I.isConditional()) {
893 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000894 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000895 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000896 Out << ") {\n";
897
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000898 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000899
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000900 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000901 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000902 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000903 }
904 } else {
905 // First goto not neccesary, assume second one is...
906 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000907 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000908 Out << ") {\n";
909
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000910 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000911 }
912
913 Out << " }\n";
914 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000915 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000916 }
917 Out << "\n";
918}
919
920
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000921void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000922 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000923 if (isa<PointerType>(I.getType())) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000924 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000925 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000926 Out << ")";
927 }
928
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000929 if (isa<PointerType>(I.getType())) Out << "(long long)";
930 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000931
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000932 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000933 case Instruction::Add: Out << " + "; break;
934 case Instruction::Sub: Out << " - "; break;
935 case Instruction::Mul: Out << "*"; break;
936 case Instruction::Div: Out << "/"; break;
937 case Instruction::Rem: Out << "%"; break;
938 case Instruction::And: Out << " & "; break;
939 case Instruction::Or: Out << " | "; break;
940 case Instruction::Xor: Out << " ^ "; break;
941 case Instruction::SetEQ: Out << " == "; break;
942 case Instruction::SetNE: Out << " != "; break;
943 case Instruction::SetLE: Out << " <= "; break;
944 case Instruction::SetGE: Out << " >= "; break;
945 case Instruction::SetLT: Out << " < "; break;
946 case Instruction::SetGT: Out << " > "; break;
947 case Instruction::Shl : Out << " << "; break;
948 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000949 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000950 }
951
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000952 if (isa<PointerType>(I.getType())) Out << "(long long)";
953 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000954}
955
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000956void CWriter::visitCastInst(CastInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000957 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000958 printType(Out, I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000959 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000960 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000961}
962
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000963void CWriter::visitCallInst(CallInst &I) {
964 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000965 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
966 const Type *RetTy = FTy->getReturnType();
967
Chris Lattnerfabc8802002-08-26 20:50:09 +0000968 writeOperand(I.getOperand(0));
969 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000970
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000971 if (I.getNumOperands() > 1) {
972 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000973
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000974 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000975 Out << ", ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000976 writeOperand(I.getOperand(op));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000977 }
978 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000979 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000980}
981
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000982void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000983 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000984 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000985 Out << ")malloc(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000986 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000987 Out << ")";
988
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000989 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000990 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000991 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000992 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000993 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000994}
995
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000996void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000997 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000998 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000999 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001000 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001001 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001002 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001003 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001004 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001005 }
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::visitFreeInst(FreeInst &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001010 Out << "free(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001011 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001012 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001013}
1014
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001015void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1016 User::op_iterator E) {
1017 bool HasImplicitAddress = false;
1018 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1019 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1020 HasImplicitAddress = true;
1021 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1022 HasImplicitAddress = true;
1023 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001024 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001025
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001026 if (I == E) {
1027 if (!HasImplicitAddress)
1028 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001029
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001030 writeOperandInternal(Ptr);
1031 return;
1032 }
1033
1034 const Constant *CI = dyn_cast<Constant>(I->get());
1035 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1036 Out << "(&";
1037
1038 writeOperandInternal(Ptr);
1039
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001040 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001041 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001042 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1043 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001044
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001045 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1046 "Can only have implicit address with direct accessing");
1047
1048 if (HasImplicitAddress) {
1049 ++I;
1050 } else if (CI && CI->isNullValue() && I+1 != E) {
1051 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001052 if ((*(I+1))->getType() == Type::UByteTy) {
1053 Out << (HasImplicitAddress ? "." : "->");
1054 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1055 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001056 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001057 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001058
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001059 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001060 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001061 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001062 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001063 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001064 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001065 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001066 }
1067}
1068
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001069void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001070 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001071 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001072}
1073
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001074void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001075 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001076 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001077 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001078 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001079}
1080
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001081void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001082 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001083 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001084}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001085
1086//===----------------------------------------------------------------------===//
1087// External Interface declaration
1088//===----------------------------------------------------------------------===//
1089
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001090Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }