blob: feaf1352695d0b50f965e58d3d93f4956768be07 [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//===-----------------------------------------------------------------------==//
Chris Lattner16c7bb22002-05-09 02:28:59 +00006
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00007#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00008#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +00009#include "llvm/DerivedTypes.h"
10#include "llvm/Module.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000011#include "llvm/iMemory.h"
12#include "llvm/iTerminators.h"
13#include "llvm/iPHINode.h"
14#include "llvm/iOther.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000015#include "llvm/iOperators.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000016#include "llvm/Pass.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/SymbolTable.h"
Chris Lattner3af3ba82002-05-09 21:31:18 +000018#include "llvm/SlotCalculator.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000019#include "llvm/Analysis/FindUsedTypes.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000020#include "llvm/Analysis/ConstantsScanner.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000021#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000022#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000023#include "Support/StringExtras.h"
24#include "Support/STLExtras.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000025#include <algorithm>
Chris Lattner78771c82002-05-17 04:55:35 +000026#include <set>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000027using std::string;
28using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000029using std::ostream;
30
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000031namespace {
Chris Lattner0e9f93e2002-08-31 00:29:16 +000032 class CWriter : public Pass, public InstVisitor<CWriter> {
33 ostream &Out;
34 SlotCalculator *Table;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035 const Module *TheModule;
36 map<const Type *, string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +000037 std::set<const Value*> MangledGlobals;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000038
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000039 map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000040 public:
Chris Lattner0e9f93e2002-08-31 00:29:16 +000041 CWriter(ostream &o) : Out(o) {}
42
43 void getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.setPreservesAll();
45 AU.addRequired<FindUsedTypes>();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000046 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000047
48 virtual bool run(Module &M) {
49 // Initialize
50 Table = new SlotCalculator(&M, false);
51 TheModule = &M;
52
53 // Ensure that all structure types have names...
54 bool Changed = nameAllUsedStructureTypes(M);
55
56 // Run...
57 printModule(&M);
58
59 // Free memory...
60 delete Table;
61 TypeNames.clear();
62 MangledGlobals.clear();
63 return false;
64 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000065
Chris Lattner83c57752002-08-19 22:17:53 +000066 ostream &printType(const Type *Ty, const string &VariableName = "",
Vikram S. Adve969c4ad2002-08-25 20:00:08 +000067 bool IgnoreName = false, bool namedContext = true);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000068
Chris Lattnerbb03efd2002-06-25 15:57:03 +000069 void writeOperand(Value *Operand);
70 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000071
72 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000073
Chris Lattner4fbf26d2002-05-09 20:53:56 +000074 private :
Chris Lattner0e9f93e2002-08-31 00:29:16 +000075 bool nameAllUsedStructureTypes(Module &M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000076 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000077 void printSymbolTable(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +000078 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 void printGlobal(const GlobalVariable *GV);
Chris Lattner4cda8352002-08-20 16:55:48 +000080 void printFunctionSignature(const Function *F, bool Prototype);
81
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000082 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000083
Chris Lattner6d492922002-08-19 21:32:41 +000084 void printConstant(Constant *CPV);
85 void printConstantArray(ConstantArray *CPA);
86
Chris Lattnerd0c668c2002-05-09 21:18:38 +000087 // isInlinableInst - Attempt to inline instructions into their uses to build
88 // trees as much as possible. To do this, we have to consistently decide
89 // what is acceptable to inline, so that variable declarations don't get
90 // printed and an extra copy of the expr is not emitted.
91 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +000092 static bool isInlinableInst(const Instruction &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +000093 // Must be an expression, must be used exactly once. If it is dead, we
94 // emit it inline where it would go.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000095 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
Chris Lattnerd0c668c2002-05-09 21:18:38 +000096 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
97 return false;
98
99 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000100 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000101 }
102
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000103 // Instruction visitation functions
104 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000105
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000106 void visitReturnInst(ReturnInst &I);
107 void visitBranchInst(BranchInst &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...
156 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//
177ostream &CWriter::printType(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);
209 printType(MTy->getReturnType(), "");
210 Out << " " << NameSoFar << " (";
211
212 for (FunctionType::ParamTypes::const_iterator
213 I = MTy->getParamTypes().begin(),
214 E = MTy->getParamTypes().end(); I != E; ++I) {
215 if (I != MTy->getParamTypes().begin())
216 Out << ", ";
217 printType(*I, "");
218 }
219 if (MTy->isVarArg()) {
220 if (!MTy->getParamTypes().empty())
221 Out << ", ";
222 Out << "...";
223 }
224 return Out << ")";
225 }
226 case Type::StructTyID: {
227 const StructType *STy = cast<StructType>(Ty);
228 Out << NameSoFar + " {\n";
229 unsigned Idx = 0;
230 for (StructType::ElementTypes::const_iterator
231 I = STy->getElementTypes().begin(),
232 E = STy->getElementTypes().end(); I != E; ++I) {
233 Out << " ";
234 printType(*I, "field" + utostr(Idx++));
235 Out << ";\n";
236 }
237 return Out << "}";
238 }
239
240 case Type::PointerTyID: {
241 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000242 std::string ptrName = "*" + NameSoFar;
243
244 // Do not need parens around "* NameSoFar" if NameSoFar consists only
245 // of zero or more '*' chars *and* this is not an unnamed pointer type
246 // such as the result type in a cast statement. Otherwise, enclose in ( ).
Nick Hildenbrandtc14ded42002-09-23 21:02:50 +0000247 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
248 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000249 ptrName = "(" + ptrName + ")"; //
250
Vikram S. Adve42eb2ba2002-08-24 14:44:23 +0000251 return printType(PTy->getElementType(), ptrName);
Chris Lattner83c57752002-08-19 22:17:53 +0000252 }
253
254 case Type::ArrayTyID: {
255 const ArrayType *ATy = cast<ArrayType>(Ty);
256 unsigned NumElements = ATy->getNumElements();
257 return printType(ATy->getElementType(),
258 NameSoFar + "[" + utostr(NumElements) + "]");
259 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000260
261 case Type::OpaqueTyID: {
262 static int Count = 0;
263 string TyName = "struct opaque_" + itostr(Count++);
264 assert(TypeNames.find(Ty) == TypeNames.end());
265 TypeNames[Ty] = TyName;
266 return Out << TyName << " " << NameSoFar;
267 }
Chris Lattner83c57752002-08-19 22:17:53 +0000268 default:
269 assert(0 && "Unhandled case in getTypeProps!");
270 abort();
271 }
272
273 return Out;
274}
275
Chris Lattner6d492922002-08-19 21:32:41 +0000276void CWriter::printConstantArray(ConstantArray *CPA) {
277
278 // As a special case, print the array as a string if it is an array of
279 // ubytes or an array of sbytes with positive values.
280 //
281 const Type *ETy = CPA->getType()->getElementType();
282 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
283
284 // Make sure the last character is a null char, as automatically added by C
285 if (CPA->getNumOperands() == 0 ||
286 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
287 isString = false;
288
289 if (isString) {
290 Out << "\"";
291 // Do not include the last character, which we know is null
292 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
293 unsigned char C = (ETy == Type::SByteTy) ?
294 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
295 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
296
297 if (isprint(C)) {
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000298 if (C == '"')
299 Out << "\\\"";
300 else
301 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000302 } else {
303 switch (C) {
304 case '\n': Out << "\\n"; break;
305 case '\t': Out << "\\t"; break;
306 case '\r': Out << "\\r"; break;
307 case '\v': Out << "\\v"; break;
308 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000309 case '\"': Out << "\\\""; break;
310 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000311 default:
312 Out << "\\x";
313 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
314 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
315 break;
316 }
317 }
318 }
319 Out << "\"";
320 } else {
321 Out << "{";
322 if (CPA->getNumOperands()) {
323 Out << " ";
324 printConstant(cast<Constant>(CPA->getOperand(0)));
325 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
326 Out << ", ";
327 printConstant(cast<Constant>(CPA->getOperand(i)));
328 }
329 }
330 Out << " }";
331 }
332}
333
334
335// printConstant - The LLVM Constant to C Constant converter.
336void CWriter::printConstant(Constant *CPV) {
337 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
338 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000339 case Instruction::Cast:
340 Out << "((";
341 printType(CPV->getType());
342 Out << ")";
343 printConstant(cast<Constant>(CPV->getOperand(0)));
344 Out << ")";
345 return;
346
347 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000348 Out << "(&(";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000349 printIndexingExpression(CPV->getOperand(0),
350 CPV->op_begin()+1, CPV->op_end());
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000351 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000352 return;
353 case Instruction::Add:
354 Out << "(";
355 printConstant(cast<Constant>(CPV->getOperand(0)));
356 Out << " + ";
357 printConstant(cast<Constant>(CPV->getOperand(1)));
358 Out << ")";
359 return;
360 case Instruction::Sub:
361 Out << "(";
362 printConstant(cast<Constant>(CPV->getOperand(0)));
363 Out << " - ";
364 printConstant(cast<Constant>(CPV->getOperand(1)));
365 Out << ")";
366 return;
367
Chris Lattner6d492922002-08-19 21:32:41 +0000368 default:
369 std::cerr << "CWriter Error: Unhandled constant expression: "
370 << CE << "\n";
371 abort();
372 }
373 }
374
375 switch (CPV->getType()->getPrimitiveID()) {
376 case Type::BoolTyID:
377 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
378 case Type::SByteTyID:
379 case Type::ShortTyID:
380 case Type::IntTyID:
381 Out << cast<ConstantSInt>(CPV)->getValue(); break;
382 case Type::LongTyID:
383 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
384
385 case Type::UByteTyID:
386 case Type::UShortTyID:
387 Out << cast<ConstantUInt>(CPV)->getValue(); break;
388 case Type::UIntTyID:
389 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
390 case Type::ULongTyID:
391 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
392
393 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000394 case Type::DoubleTyID: {
395 ConstantFP *FPC = cast<ConstantFP>(CPV);
396 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
397 if (I != FPConstantMap.end()) {
398 // Because of FP precision problems we must load from a stack allocated
399 // value that holds the value in hex.
400 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
401 << "*)&FloatConstant" << I->second << ")";
402 } else {
403 Out << FPC->getValue();
404 }
405 break;
406 }
Chris Lattner6d492922002-08-19 21:32:41 +0000407
408 case Type::ArrayTyID:
409 printConstantArray(cast<ConstantArray>(CPV));
410 break;
411
412 case Type::StructTyID: {
413 Out << "{";
414 if (CPV->getNumOperands()) {
415 Out << " ";
416 printConstant(cast<Constant>(CPV->getOperand(0)));
417 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
418 Out << ", ";
419 printConstant(cast<Constant>(CPV->getOperand(i)));
420 }
421 }
422 Out << " }";
423 break;
424 }
425
426 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000427 if (isa<ConstantPointerNull>(CPV)) {
428 Out << "((";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000429 printType(CPV->getType(), "");
Chris Lattner4fbf26d2002-05-09 20:53:56 +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
Chris Lattner6d492922002-08-19 21:32:41 +0000453 if (Operand->hasName()) {
454 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 //
485 SymbolTable *MST = M.getSymbolTableSure();
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)
489 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)) {
498 ((Value*)ST)->setName("unnamed", MST);
499 Changed = true;
500 }
501 return Changed;
502}
503
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000504void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000505 // Calculate which global values have names that will collide when we throw
506 // away type information.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000507 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattner78771c82002-05-17 04:55:35 +0000508 std::set<string> FoundNames;
509 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000510 if (I->hasName()) // If the global has a name...
511 if (FoundNames.count(I->getName())) // And the name is already used
512 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000513 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000514 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000515
516 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000517 if (I->hasName()) // If the global has a name...
518 if (FoundNames.count(I->getName())) // And the name is already used
519 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000520 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000521 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000522 }
523
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000524 // printing stdlib inclusion
Nick Hildenbrandt98360a12002-10-11 21:40:44 +0000525 //Out << "#include <stdlib.h>\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000526
Chris Lattner16c7bb22002-05-09 02:28:59 +0000527 // get declaration for alloca
528 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000529 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000530
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000531 // Provide a definition for null if one does not already exist,
532 // and for `bool' if not compiling with a C++ compiler.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000533 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000534 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000535
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000536 << "\n\n/* Support for floating point constants */\n"
537 << "typedef unsigned long long ConstantDoubleTy;\n"
538
Chris Lattnera4d4a852002-08-19 21:48:40 +0000539 << "\n\n/* Global Declarations */\n";
540
541 // First output all the declarations for the program, because C requires
542 // Functions & globals to be declared before they are used.
543 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000544
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000545 // Loop over the symbol table, emitting all named constants...
546 if (M->hasSymbolTable())
547 printSymbolTable(*M->getSymbolTable());
548
Chris Lattnera4d4a852002-08-19 21:48:40 +0000549 // Global variable declarations...
550 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000551 Out << "\n/* External Global Variable Declarations */\n";
Nick Hildenbrandt98360a12002-10-11 21:40:44 +0000552 // Needed for malloc to work on sun.
553 Out << "extern void * malloc(size_t);\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000554 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000555 if (I->hasExternalLinkage()) {
556 Out << "extern ";
557 printType(I->getType()->getElementType(), getValueName(I));
558 Out << ";\n";
559 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000560 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000561 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000562
Chris Lattnera4d4a852002-08-19 21:48:40 +0000563 // Function declarations
564 if (!M->empty()) {
565 Out << "\n/* Function Declarations */\n";
Chris Lattner4cda8352002-08-20 16:55:48 +0000566 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
567 printFunctionSignature(I, true);
568 Out << ";\n";
569 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000570 }
571
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000572 // Output the global variable definitions and contents...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000573 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000574 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000575 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve2a408f02002-10-05 23:43:10 +0000576 if (I->hasInternalLinkage())
577 Out << "static ";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000578 printType(I->getType()->getElementType(), getValueName(I));
579
580 if (I->hasInitializer()) {
581 Out << " = " ;
582 writeOperand(I->getInitializer());
583 }
584 Out << ";\n";
585 }
586 }
587
Chris Lattner16c7bb22002-05-09 02:28:59 +0000588 // Output all of the functions...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000589 if (!M->empty()) {
590 Out << "\n\n/* Function Bodies */\n";
591 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
592 printFunction(I);
593 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000594}
595
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000596
Chris Lattner2db41cd2002-09-20 15:12:13 +0000597/// printSymbolTable - Run through symbol table looking for type names. If a
598/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000599///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000600void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000601 // If there are no type names, exit early.
602 if (ST.find(Type::TypeTy) == ST.end())
603 return;
604
605 // We are only interested in the type plane of the symbol table...
606 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
607 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
608
Chris Lattner58d04d42002-09-20 15:18:30 +0000609 // Print out forward declarations for structure types before anything else!
610 Out << "/* Structure forward decls */\n";
611 for (; I != End; ++I)
612 if (const Type *STy = dyn_cast<StructType>(I->second)) {
613 string Name = "struct l_" + makeNameProper(I->first);
614 Out << Name << ";\n";
615 TypeNames.insert(std::make_pair(STy, Name));
616 }
617
618 Out << "\n";
619
620 // Now we can print out typedefs...
621 Out << "/* Typedefs */\n";
622 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
623 const Type *Ty = cast<Type>(I->second);
624 string Name = "l_" + makeNameProper(I->first);
625 Out << "typedef ";
Chris Lattner270d78a2002-09-20 15:20:24 +0000626 printType(Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000627 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000628 }
629
630 Out << "\n";
631
Chris Lattner2c601a72002-09-20 15:05:40 +0000632 // Keep track of which structures have been printed so far...
633 std::set<const StructType *> StructPrinted;
634
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000635 // Loop over all structures then push them into the stack so they are
636 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000637 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000638 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000639 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
640 if (const StructType *STy = dyn_cast<StructType>(I->second))
641 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000642}
643
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000644// Push the struct onto the stack and recursively push all structs
645// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000646void CWriter::printContainedStructs(const Type *Ty,
647 std::set<const StructType*> &StructPrinted){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000648 if (const StructType *STy = dyn_cast<StructType>(Ty)){
649 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000650 if (StructPrinted.count(STy) == 0) {
651 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000652 for (StructType::ElementTypes::const_iterator
653 I = STy->getElementTypes().begin(),
654 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000655 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000656 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000657 printContainedStructs(Ty1, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000658 }
659
Chris Lattner2c601a72002-09-20 15:05:40 +0000660 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000661 StructPrinted.insert(STy);
662 string Name = TypeNames[STy];
663 printType(STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000664 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000665 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000666
Chris Lattner2c601a72002-09-20 15:05:40 +0000667 // If it is an array, check contained types and continue
668 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000669 const Type *Ty1 = ATy->getElementType();
670 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000671 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000672 }
673}
674
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000675
Chris Lattner4cda8352002-08-20 16:55:48 +0000676void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000677 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000678
679 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000680 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000681
Chris Lattner16c7bb22002-05-09 02:28:59 +0000682 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000683 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000684 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000685
Chris Lattner16c7bb22002-05-09 02:28:59 +0000686 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000687 if (!F->aempty()) {
Chris Lattner4cda8352002-08-20 16:55:48 +0000688 string ArgName;
689 if (F->abegin()->hasName() || !Prototype)
690 ArgName = getValueName(F->abegin());
691
692 printType(F->afront().getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000693
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000694 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
695 I != E; ++I) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000696 Out << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000697 if (I->hasName() || !Prototype)
698 ArgName = getValueName(I);
699 else
700 ArgName = "";
701 printType(I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000702 }
703 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000704 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000705 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000706 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000707 FT->getParamTypes().begin(),
708 E = FT->getParamTypes().end(); I != E; ++I) {
709 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000710 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000711 }
712 }
713
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000714 // Finish printing arguments... if this is a vararg function, print the ...,
715 // unless there are no known types, in which case, we just emit ().
716 //
717 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000718 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000719 Out << "..."; // Output varargs portion of signature!
720 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000721 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000722}
723
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000724
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000725void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000726 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000727
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000728 Table->incorporateFunction(F);
Chris Lattnerf34ee812002-05-09 03:12:34 +0000729
Chris Lattner4cda8352002-08-20 16:55:48 +0000730 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000731 Out << " {\n";
732
Chris Lattner497e19a2002-05-09 20:39:03 +0000733 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000734 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000735 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000736 Out << " ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000737 printType((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000738 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000739 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000740
741 Out << "\n";
742
743 // Scan the function for floating point constants. If any FP constant is used
744 // in the function, we want to redirect it here so that we do not depend on
745 // the precision of the printed form.
746 //
747 unsigned FPCounter = 0;
748 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
749 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
750 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
751 double Val = FPC->getValue();
752
753 FPConstantMap[FPC] = FPCounter; // Number the FP constants
754 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
755 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
756 << "; /* " << Val << " */\n";
757 }
758
759 Out << "\n";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000760
761 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000762 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
763 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000764
765 // Don't print the label for the basic block if there are no uses, or if the
766 // only terminator use is the precessor basic block's terminator. We have
767 // to scan the use list because PHI nodes use basic blocks too but do not
768 // require a label to be generated.
769 //
770 bool NeedsLabel = false;
771 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
772 UI != UE; ++UI)
773 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
774 if (TI != Prev->getTerminator()) {
775 NeedsLabel = true;
776 break;
777 }
778
779 if (NeedsLabel) Out << getValueName(BB) << ":\n";
780
781 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000782 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000783 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000784 if (II->getType() != Type::VoidTy)
785 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000786 else
787 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000788 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000789 Out << ";\n";
790 }
791 }
792
793 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000794 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000795 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000796
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000797 Out << "}\n\n";
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000798 Table->purgeFunction();
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000799 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000800}
801
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000802// Specific Instruction type classes... note that all of the casts are
803// neccesary because we use the instruction classes as opaque types...
804//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000805void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000806 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000807 if (I.getNumOperands() == 0 &&
808 &*--I.getParent()->getParent()->end() == I.getParent() &&
809 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000810 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000811 }
Chris Lattner44408262002-05-09 03:50:42 +0000812
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000813 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000814 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000815 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000816 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000817 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000818 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000819}
820
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000821static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
822 // If PHI nodes need copies, we need the copy code...
823 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000824 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000825 return true;
826
827 // Otherwise we don't need the code.
828 return false;
829}
830
831void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
832 unsigned Indent) {
833 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000834 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000835 // now we have to do the printing
836 Out << string(Indent, ' ');
837 outputLValue(PN);
838 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
839 Out << "; /* for PHI node */\n";
840 }
841
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000842 if (CurBB->getNext() != Succ) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000843 Out << string(Indent, ' ') << " goto ";
844 writeOperand(Succ);
845 Out << ";\n";
846 }
847}
848
849// Brach instruction printing - Avoid printing out a brach to a basic block that
850// immediately succeeds the current one.
851//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000852void CWriter::visitBranchInst(BranchInst &I) {
853 if (I.isConditional()) {
854 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000855 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000856 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000857 Out << ") {\n";
858
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000859 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000860
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000861 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000862 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000863 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000864 }
865 } else {
866 // First goto not neccesary, assume second one is...
867 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000868 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000869 Out << ") {\n";
870
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000871 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000872 }
873
874 Out << " }\n";
875 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000876 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000877 }
878 Out << "\n";
879}
880
881
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000882void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000883 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000884 if (isa<PointerType>(I.getType())) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000885 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000886 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000887 Out << ")";
888 }
889
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000890 if (isa<PointerType>(I.getType())) Out << "(long long)";
891 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000892
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000893 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000894 case Instruction::Add: Out << " + "; break;
895 case Instruction::Sub: Out << " - "; break;
896 case Instruction::Mul: Out << "*"; break;
897 case Instruction::Div: Out << "/"; break;
898 case Instruction::Rem: Out << "%"; break;
899 case Instruction::And: Out << " & "; break;
900 case Instruction::Or: Out << " | "; break;
901 case Instruction::Xor: Out << " ^ "; break;
902 case Instruction::SetEQ: Out << " == "; break;
903 case Instruction::SetNE: Out << " != "; break;
904 case Instruction::SetLE: Out << " <= "; break;
905 case Instruction::SetGE: Out << " >= "; break;
906 case Instruction::SetLT: Out << " < "; break;
907 case Instruction::SetGT: Out << " > "; break;
908 case Instruction::Shl : Out << " << "; break;
909 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000910 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000911 }
912
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000913 if (isa<PointerType>(I.getType())) Out << "(long long)";
914 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000915}
916
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000917void CWriter::visitCastInst(CastInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000918 Out << "(";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000919 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000920 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000921 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000922}
923
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000924void CWriter::visitCallInst(CallInst &I) {
925 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000926 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
927 const Type *RetTy = FTy->getReturnType();
928
Chris Lattnerfabc8802002-08-26 20:50:09 +0000929 writeOperand(I.getOperand(0));
930 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000931
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000932 if (I.getNumOperands() > 1) {
933 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000934
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000935 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000936 Out << ", ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000937 writeOperand(I.getOperand(op));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000938 }
939 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000940 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000941}
942
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000943void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000944 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000945 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000946 Out << ")malloc(sizeof(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000947 printType(I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000948 Out << ")";
949
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000950 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000951 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000952 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000953 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000954 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000955}
956
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000957void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000958 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000959 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000960 Out << ") alloca(sizeof(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000961 printType(I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000962 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000963 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000964 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000965 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000966 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000967 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000968}
969
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000970void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000971 Out << "free(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000972 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000973 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000974}
975
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000976void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
977 User::op_iterator E) {
978 bool HasImplicitAddress = false;
979 // If accessing a global value with no indexing, avoid *(&GV) syndrome
980 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
981 HasImplicitAddress = true;
982 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
983 HasImplicitAddress = true;
984 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000985 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000986
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000987 if (I == E) {
988 if (!HasImplicitAddress)
989 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000990
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000991 writeOperandInternal(Ptr);
992 return;
993 }
994
995 const Constant *CI = dyn_cast<Constant>(I->get());
996 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
997 Out << "(&";
998
999 writeOperandInternal(Ptr);
1000
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001001 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001002 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001003 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1004 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001005
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001006 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1007 "Can only have implicit address with direct accessing");
1008
1009 if (HasImplicitAddress) {
1010 ++I;
1011 } else if (CI && CI->isNullValue() && I+1 != E) {
1012 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001013 if ((*(I+1))->getType() == Type::UByteTy) {
1014 Out << (HasImplicitAddress ? "." : "->");
1015 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1016 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001017 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001018 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001019
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001020 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001021 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001022 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001023 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001024 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001025 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001026 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001027 }
1028}
1029
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001030void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001031 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001032 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001033}
1034
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001035void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001036 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001037 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001038 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001039 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001040}
1041
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001042void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001043 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001044 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001045}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001046
1047//===----------------------------------------------------------------------===//
1048// External Interface declaration
1049//===----------------------------------------------------------------------===//
1050
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001051Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }