blob: 88113a0347a0e83fcd41bebb04e9119283590732 [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Misha Brukmand6a29a52005-04-20 16:05:03 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmand6a29a52005-04-20 16:05:03 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00009//
Chris Lattner897bf0d2004-02-13 06:18:21 +000010// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
Chris Lattner16c7bb22002-05-09 02:28:59 +000012//
Chris Lattneredd8ce12003-05-03 03:14:35 +000013//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +000014
Chris Lattnerf31182a2004-02-13 23:18:48 +000015#include "CTargetMachine.h"
Chris Lattner0c54d892006-05-23 23:39:48 +000016#include "llvm/CallingConv.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000020#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000021#include "llvm/Pass.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000022#include "llvm/PassManager.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000023#include "llvm/SymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000024#include "llvm/Intrinsics.h"
Jim Laskey580418e2006-03-23 18:08:29 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000026#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000027#include "llvm/Analysis/FindUsedTypes.h"
28#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000029#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000031#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000032#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000033#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000036#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000037#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000039#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/Support/MathExtras.h"
41#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000042#include <algorithm>
Reid Spencer954da372004-07-04 12:19:56 +000043#include <iostream>
Duraid Madinad2dec7d2005-12-27 10:40:34 +000044#include <ios>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000045#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000048namespace {
Chris Lattnerd36c9702004-07-11 02:48:49 +000049 // Register the target.
Chris Lattner71d24aa2004-07-11 03:27:42 +000050 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000051
Chris Lattnerf9a05322006-02-13 22:22:42 +000052 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53 /// any unnamed structure types that are used by the program, and merges
54 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000055 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000056 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Chris Lattner68758072004-05-09 06:20:51 +000057 void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<FindUsedTypes>();
59 }
60
61 virtual const char *getPassName() const {
62 return "C backend type canonicalizer";
63 }
64
Chris Lattnerb12914b2004-09-20 04:48:05 +000065 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000066 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000067
Chris Lattner68758072004-05-09 06:20:51 +000068 /// CWriter - This class is the main chunk of code that converts an LLVM
69 /// module to a C translation unit.
70 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmand6a29a52005-04-20 16:05:03 +000071 std::ostream &Out;
Chris Lattnerbc641b92006-03-23 05:43:16 +000072 DefaultIntrinsicLowering IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000073 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000074 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000075 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000076 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000077
Chris Lattneredd8ce12003-05-03 03:14:35 +000078 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 public:
Chris Lattnerbc641b92006-03-23 05:43:16 +000080 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000081
Chris Lattner94f4f8e2004-02-13 23:00:29 +000082 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000083
Chris Lattnercb3ad012004-05-09 20:41:32 +000084 void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.setPreservesAll();
87 }
88
Chris Lattner68758072004-05-09 06:20:51 +000089 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000090
Chris Lattner68758072004-05-09 06:20:51 +000091 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000092 LI = &getAnalysis<LoopInfo>();
93
Chris Lattner3150e2d2004-12-05 06:49:44 +000094 // Get rid of intrinsics we can't handle.
95 lowerIntrinsics(F);
96
Chris Lattner68758072004-05-09 06:20:51 +000097 // Output all floating point constants that cannot be printed accurately.
98 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +000099
100 // Ensure that no local symbols conflict with global symbols.
101 F.renameLocalSymbols();
102
Chris Lattner68758072004-05-09 06:20:51 +0000103 printFunction(F);
104 FPConstantMap.clear();
105 return false;
106 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000107
Chris Lattner68758072004-05-09 06:20:51 +0000108 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000109 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000110 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000111 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000112 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000113 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000114
Chris Lattneredd8ce12003-05-03 03:14:35 +0000115 std::ostream &printType(std::ostream &Out, const Type *Ty,
116 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000117 bool IgnoreName = false);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000118
Chris Lattner0c54d892006-05-23 23:39:48 +0000119 void printStructReturnPointerFunctionType(std::ostream &Out,
120 const PointerType *Ty);
121
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000122 void writeOperand(Value *Operand);
123 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000124
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000125 private :
Chris Lattnerc2421432004-05-09 04:30:20 +0000126 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000127
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000128 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000129 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000130 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000131 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000132 void printFunctionSignature(const Function *F, bool Prototype);
133
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000134 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000135 void printBasicBlock(BasicBlock *BB);
136 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000137
Chris Lattner6d492922002-08-19 21:32:41 +0000138 void printConstant(Constant *CPV);
139 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000140 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000141
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000142 // isInlinableInst - Attempt to inline instructions into their uses to build
143 // trees as much as possible. To do this, we have to consistently decide
144 // what is acceptable to inline, so that variable declarations don't get
145 // printed and an extra copy of the expr is not emitted.
146 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000147 static bool isInlinableInst(const Instruction &I) {
Chris Lattner433e25a2004-05-20 20:25:50 +0000148 // Always inline setcc instructions, even if they are shared by multiple
149 // expressions. GCC generates horrible code if we don't.
150 if (isa<SetCondInst>(I)) return true;
151
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000152 // Must be an expression, must be used exactly once. If it is dead, we
153 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000154 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000155 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000156 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000157 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000158 return false;
159
160 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000161 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000162 }
163
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000164 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
165 // variables which are accessed with the & operator. This causes GCC to
166 // generate significantly better code than to emit alloca calls directly.
167 //
168 static const AllocaInst *isDirectAlloca(const Value *V) {
169 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
170 if (!AI) return false;
171 if (AI->isArrayAllocation())
172 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000173 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000174 return 0;
175 return AI;
176 }
177
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000178 // Instruction visitation functions
179 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000180
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000181 void visitReturnInst(ReturnInst &I);
182 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000183 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000184 void visitInvokeInst(InvokeInst &I) {
185 assert(0 && "Lowerinvoke pass didn't work!");
186 }
187
188 void visitUnwindInst(UnwindInst &I) {
189 assert(0 && "Lowerinvoke pass didn't work!");
190 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000191 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000192
Chris Lattner84e66652003-05-03 07:11:00 +0000193 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000194 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000195
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000196 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000197 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000198 void visitCallInst (CallInst &I);
199 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000200
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000201 void visitMallocInst(MallocInst &I);
202 void visitAllocaInst(AllocaInst &I);
203 void visitFreeInst (FreeInst &I);
204 void visitLoadInst (LoadInst &I);
205 void visitStoreInst (StoreInst &I);
206 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000207 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000208
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000209 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000210 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000211 abort();
212 }
213
214 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000215 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000216 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000217
218 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000219 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
220 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000221 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
222 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000223 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
224 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000225 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000226}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000227
Chris Lattner68758072004-05-09 06:20:51 +0000228/// This method inserts names for any unnamed structure types that are used by
229/// the program, and removes names from structure types that are not used by the
230/// program.
231///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000232bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000233 // Get a set of types that are used by the program...
234 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000235
Chris Lattner68758072004-05-09 06:20:51 +0000236 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000237 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000238 //
239 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000240 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
241 TI != TE; ) {
242 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000243
244 // If this is not used, remove it from the symbol table.
245 std::set<const Type *>::iterator UTI = UT.find(I->second);
246 if (UTI == UT.end())
247 MST.remove(I);
248 else
249 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000250 }
Chris Lattner68758072004-05-09 06:20:51 +0000251
252 // UT now contains types that are not named. Loop over it, naming
253 // structure types.
254 //
255 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000256 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000257 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
258 I != E; ++I)
259 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000260 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
261 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000262 Changed = true;
263 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000264
265
266 // Loop over all external functions and globals. If we have two with
267 // identical names, merge them.
268 // FIXME: This code should disappear when we don't allow values with the same
269 // names when they have different types!
270 std::map<std::string, GlobalValue*> ExtSymbols;
271 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
272 Function *GV = I++;
273 if (GV->isExternal() && GV->hasName()) {
274 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
275 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
276 if (!X.second) {
277 // Found a conflict, replace this global with the previous one.
278 GlobalValue *OldGV = X.first->second;
279 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
280 GV->eraseFromParent();
281 Changed = true;
282 }
283 }
284 }
285 // Do the same for globals.
286 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
287 I != E;) {
288 GlobalVariable *GV = I++;
289 if (GV->isExternal() && GV->hasName()) {
290 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
291 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
292 if (!X.second) {
293 // Found a conflict, replace this global with the previous one.
294 GlobalValue *OldGV = X.first->second;
295 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
296 GV->eraseFromParent();
297 Changed = true;
298 }
299 }
300 }
301
Chris Lattner68758072004-05-09 06:20:51 +0000302 return Changed;
303}
304
Chris Lattner0c54d892006-05-23 23:39:48 +0000305/// printStructReturnPointerFunctionType - This is like printType for a struct
306/// return type, except, instead of printing the type as void (*)(Struct*, ...)
307/// print it as "Struct (*)(...)", for struct return functions.
308void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
309 const PointerType *TheTy) {
310 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
311 std::stringstream FunctionInnards;
312 FunctionInnards << " (*) (";
313 bool PrintedType = false;
314
315 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
316 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
317 for (++I; I != E; ++I) {
318 if (PrintedType)
319 FunctionInnards << ", ";
320 printType(FunctionInnards, *I, "");
321 PrintedType = true;
322 }
323 if (FTy->isVarArg()) {
324 if (PrintedType)
325 FunctionInnards << ", ...";
326 } else if (!PrintedType) {
327 FunctionInnards << "void";
328 }
329 FunctionInnards << ')';
330 std::string tstr = FunctionInnards.str();
331 printType(Out, RetTy, tstr);
332}
333
Chris Lattner68758072004-05-09 06:20:51 +0000334
Chris Lattner83c57752002-08-19 22:17:53 +0000335// Pass the Type* and the variable name and this prints out the variable
336// declaration.
337//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000338std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
339 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000340 bool IgnoreName) {
Chris Lattner83c57752002-08-19 22:17:53 +0000341 if (Ty->isPrimitiveType())
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000342 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000343 case Type::VoidTyID: return Out << "void " << NameSoFar;
344 case Type::BoolTyID: return Out << "bool " << NameSoFar;
345 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
346 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
347 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
348 case Type::ShortTyID: return Out << "short " << NameSoFar;
349 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
350 case Type::IntTyID: return Out << "int " << NameSoFar;
351 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
352 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
353 case Type::FloatTyID: return Out << "float " << NameSoFar;
354 case Type::DoubleTyID: return Out << "double " << NameSoFar;
355 default :
Chris Lattner76e2df22004-07-15 02:14:30 +0000356 std::cerr << "Unknown primitive type: " << *Ty << "\n";
Chris Lattner83c57752002-08-19 22:17:53 +0000357 abort();
358 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000359
Chris Lattner83c57752002-08-19 22:17:53 +0000360 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000361 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000362 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000363 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000364 }
Chris Lattner83c57752002-08-19 22:17:53 +0000365
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000366 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000367 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000368 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000369 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000370 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner0c54d892006-05-23 23:39:48 +0000371 for (FunctionType::param_iterator I = FTy->param_begin(),
372 E = FTy->param_end(); I != E; ++I) {
373 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000374 FunctionInnards << ", ";
375 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000376 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000377 if (FTy->isVarArg()) {
378 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000379 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000380 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000381 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000382 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000383 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000384 std::string tstr = FunctionInnards.str();
Chris Lattner0c54d892006-05-23 23:39:48 +0000385 printType(Out, FTy->getReturnType(), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000386 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000387 }
388 case Type::StructTyID: {
389 const StructType *STy = cast<StructType>(Ty);
390 Out << NameSoFar + " {\n";
391 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000392 for (StructType::element_iterator I = STy->element_begin(),
393 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000394 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000395 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000396 Out << ";\n";
397 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000398 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000399 }
Chris Lattner83c57752002-08-19 22:17:53 +0000400
401 case Type::PointerTyID: {
402 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000403 std::string ptrName = "*" + NameSoFar;
404
Robert Bocchinob78e8382006-01-20 20:43:57 +0000405 if (isa<ArrayType>(PTy->getElementType()) ||
406 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000407 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000408
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000409 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000410 }
Chris Lattner83c57752002-08-19 22:17:53 +0000411
412 case Type::ArrayTyID: {
413 const ArrayType *ATy = cast<ArrayType>(Ty);
414 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000415 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000416 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000417 NameSoFar + "[" + utostr(NumElements) + "]");
418 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000419
Robert Bocchinob78e8382006-01-20 20:43:57 +0000420 case Type::PackedTyID: {
421 const PackedType *PTy = cast<PackedType>(Ty);
422 unsigned NumElements = PTy->getNumElements();
423 if (NumElements == 0) NumElements = 1;
424 return printType(Out, PTy->getElementType(),
425 NameSoFar + "[" + utostr(NumElements) + "]");
426 }
427
Chris Lattner04b72c82002-10-16 00:08:22 +0000428 case Type::OpaqueTyID: {
429 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000430 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000431 assert(TypeNames.find(Ty) == TypeNames.end());
432 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000433 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000434 }
Chris Lattner83c57752002-08-19 22:17:53 +0000435 default:
436 assert(0 && "Unhandled case in getTypeProps!");
437 abort();
438 }
439
440 return Out;
441}
442
Chris Lattner6d492922002-08-19 21:32:41 +0000443void CWriter::printConstantArray(ConstantArray *CPA) {
444
445 // As a special case, print the array as a string if it is an array of
446 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000447 //
Chris Lattner6d492922002-08-19 21:32:41 +0000448 const Type *ETy = CPA->getType()->getElementType();
449 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
450
451 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000452 if (isString && (CPA->getNumOperands() == 0 ||
453 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000454 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000455
Chris Lattner6d492922002-08-19 21:32:41 +0000456 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000457 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000458 // Keep track of whether the last number was a hexadecimal escape
459 bool LastWasHex = false;
460
Chris Lattner6d492922002-08-19 21:32:41 +0000461 // Do not include the last character, which we know is null
462 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000463 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000464
Chris Lattner02da6c02003-06-16 12:09:09 +0000465 // Print it out literally if it is a printable character. The only thing
466 // to be careful about is when the last letter output was a hex escape
467 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000468 // explicitly (the C compiler thinks it is a continuation of the previous
469 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000470 //
471 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
472 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000473 if (C == '"' || C == '\\')
474 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000475 else
476 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000477 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000478 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000479 switch (C) {
480 case '\n': Out << "\\n"; break;
481 case '\t': Out << "\\t"; break;
482 case '\r': Out << "\\r"; break;
483 case '\v': Out << "\\v"; break;
484 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000485 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000486 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000487 default:
488 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000489 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
490 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
491 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000492 break;
493 }
494 }
495 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000496 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000497 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000498 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000499 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000500 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000501 printConstant(cast<Constant>(CPA->getOperand(0)));
502 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
503 Out << ", ";
504 printConstant(cast<Constant>(CPA->getOperand(i)));
505 }
506 }
507 Out << " }";
508 }
509}
510
Robert Bocchinob78e8382006-01-20 20:43:57 +0000511void CWriter::printConstantPacked(ConstantPacked *CP) {
512 Out << '{';
513 if (CP->getNumOperands()) {
514 Out << ' ';
515 printConstant(cast<Constant>(CP->getOperand(0)));
516 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
517 Out << ", ";
518 printConstant(cast<Constant>(CP->getOperand(i)));
519 }
520 }
521 Out << " }";
522}
523
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000524// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
525// textually as a double (rather than as a reference to a stack-allocated
526// variable). We decide this by converting CFP to a string and back into a
527// double, and then checking whether the conversion results in a bit-equal
528// double to the original value of CFP. This depends on us and the target C
529// compiler agreeing on the conversion process (which is pretty likely since we
530// only deal in IEEE FP).
531//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000532static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Chris Lattner4946a8c2003-10-13 17:13:53 +0000533#if HAVE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000534 char Buffer[100];
535 sprintf(Buffer, "%a", CFP->getValue());
536
537 if (!strncmp(Buffer, "0x", 2) ||
538 !strncmp(Buffer, "-0x", 3) ||
539 !strncmp(Buffer, "+0x", 3))
540 return atof(Buffer) == CFP->getValue();
541 return false;
542#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000543 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000544
545 while (StrVal[0] == ' ')
546 StrVal.erase(StrVal.begin());
547
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000548 // Check to make sure that the stringized number is not some string like "Inf"
549 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000550 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
551 ((StrVal[0] == '-' || StrVal[0] == '+') &&
552 (StrVal[1] >= '0' && StrVal[1] <= '9')))
553 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000554 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000555 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000556#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000557}
Chris Lattner6d492922002-08-19 21:32:41 +0000558
559// printConstant - The LLVM Constant to C Constant converter.
560void CWriter::printConstant(Constant *CPV) {
561 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
562 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000563 case Instruction::Cast:
564 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000565 printType(Out, CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000566 Out << ')';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000567 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000568 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000569 return;
570
571 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000572 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000573 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
574 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000575 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000576 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000577 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000578 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000579 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000580 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000581 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000582 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000583 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000584 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000585 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000586 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000587 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000588 case Instruction::Mul:
589 case Instruction::Div:
590 case Instruction::Rem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000591 case Instruction::And:
592 case Instruction::Or:
593 case Instruction::Xor:
Chris Lattner29255922003-08-14 19:19:53 +0000594 case Instruction::SetEQ:
595 case Instruction::SetNE:
596 case Instruction::SetLT:
597 case Instruction::SetLE:
598 case Instruction::SetGT:
599 case Instruction::SetGE:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000600 case Instruction::Shl:
601 case Instruction::Shr:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000602 Out << '(';
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000603 printConstant(CE->getOperand(0));
Chris Lattner29255922003-08-14 19:19:53 +0000604 switch (CE->getOpcode()) {
605 case Instruction::Add: Out << " + "; break;
606 case Instruction::Sub: Out << " - "; break;
607 case Instruction::Mul: Out << " * "; break;
608 case Instruction::Div: Out << " / "; break;
609 case Instruction::Rem: Out << " % "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000610 case Instruction::And: Out << " & "; break;
611 case Instruction::Or: Out << " | "; break;
612 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000613 case Instruction::SetEQ: Out << " == "; break;
614 case Instruction::SetNE: Out << " != "; break;
615 case Instruction::SetLT: Out << " < "; break;
616 case Instruction::SetLE: Out << " <= "; break;
617 case Instruction::SetGT: Out << " > "; break;
618 case Instruction::SetGE: Out << " >= "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000619 case Instruction::Shl: Out << " << "; break;
620 case Instruction::Shr: Out << " >> "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000621 default: assert(0 && "Illegal opcode here!");
622 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000623 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000624 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000625 return;
626
Chris Lattner6d492922002-08-19 21:32:41 +0000627 default:
628 std::cerr << "CWriter Error: Unhandled constant expression: "
Chris Lattner76e2df22004-07-15 02:14:30 +0000629 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000630 abort();
631 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000632 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000633 Out << "((";
634 printType(Out, CPV->getType());
635 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000636 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000637 }
638
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000639 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000640 case Type::BoolTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000641 Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
642 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000643 case Type::SByteTyID:
644 case Type::ShortTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000645 Out << cast<ConstantSInt>(CPV)->getValue();
646 break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000647 case Type::IntTyID:
648 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
Chris Lattner40e7c352004-11-30 21:33:58 +0000649 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
Chris Lattner45343ea2003-05-12 15:39:31 +0000650 else
651 Out << cast<ConstantSInt>(CPV)->getValue();
652 break;
653
Chris Lattner6d492922002-08-19 21:32:41 +0000654 case Type::LongTyID:
Chris Lattner40e7c352004-11-30 21:33:58 +0000655 if (cast<ConstantSInt>(CPV)->isMinValue())
656 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
657 else
Chris Lattner33ce7772006-09-28 23:19:29 +0000658 Out << cast<ConstantSInt>(CPV)->getValue() << "ll";
659 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000660
661 case Type::UByteTyID:
662 case Type::UShortTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000663 Out << cast<ConstantUInt>(CPV)->getValue();
664 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000665 case Type::UIntTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000666 Out << cast<ConstantUInt>(CPV)->getValue() << 'u';
667 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000668 case Type::ULongTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000669 Out << cast<ConstantUInt>(CPV)->getValue() << "ull";
670 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000671
672 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000673 case Type::DoubleTyID: {
674 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000675 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000676 if (I != FPConstantMap.end()) {
677 // Because of FP precision problems we must load from a stack allocated
678 // value that holds the value in hex.
679 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000680 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000681 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000682 if (IsNAN(FPC->getValue())) {
683 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000684
Brian Gaeke8a702e82004-08-25 19:00:42 +0000685 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
686 // it's 0x7ff4.
687 const unsigned long QuietNaN = 0x7ff8UL;
688 const unsigned long SignalNaN = 0x7ff4UL;
689
690 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000691 char Buffer[100];
692
Jim Laskeycb6682f2005-08-17 19:34:49 +0000693 uint64_t ll = DoubleToBits(FPC->getValue());
Reid Spencer2bc320d2006-05-31 22:26:11 +0000694 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +0000695
696 std::string Num(&Buffer[0], &Buffer[6]);
697 unsigned long Val = strtoul(Num.c_str(), 0, 16);
698
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000699 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000700 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
701 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000702 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000703 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
704 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000705 } else if (IsInf(FPC->getValue())) {
706 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000707 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000708 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
709 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000710 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000711 std::string Num;
712#if HAVE_PRINTF_A
713 // Print out the constant as a floating point number.
714 char Buffer[100];
715 sprintf(Buffer, "%a", FPC->getValue());
716 Num = Buffer;
717#else
718 Num = ftostr(FPC->getValue());
719#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000720 Out << Num;
721 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000722 }
723 break;
724 }
Chris Lattner6d492922002-08-19 21:32:41 +0000725
726 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000727 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000728 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000729 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000730 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000731 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000732 Constant *CZ = Constant::getNullValue(AT->getElementType());
733 printConstant(CZ);
734 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
735 Out << ", ";
736 printConstant(CZ);
737 }
738 }
739 Out << " }";
740 } else {
741 printConstantArray(cast<ConstantArray>(CPV));
742 }
Chris Lattner6d492922002-08-19 21:32:41 +0000743 break;
744
Robert Bocchinob78e8382006-01-20 20:43:57 +0000745 case Type::PackedTyID:
746 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
747 const PackedType *AT = cast<PackedType>(CPV->getType());
748 Out << '{';
749 if (AT->getNumElements()) {
750 Out << ' ';
751 Constant *CZ = Constant::getNullValue(AT->getElementType());
752 printConstant(CZ);
753 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
754 Out << ", ";
755 printConstant(CZ);
756 }
757 }
758 Out << " }";
759 } else {
760 printConstantPacked(cast<ConstantPacked>(CPV));
761 }
762 break;
763
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000764 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000765 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000766 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000767 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000768 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000769 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000770 printConstant(Constant::getNullValue(ST->getElementType(0)));
771 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
772 Out << ", ";
773 printConstant(Constant::getNullValue(ST->getElementType(i)));
774 }
Chris Lattner6d492922002-08-19 21:32:41 +0000775 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000776 Out << " }";
777 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000778 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000779 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000780 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000781 printConstant(cast<Constant>(CPV->getOperand(0)));
782 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
783 Out << ", ";
784 printConstant(cast<Constant>(CPV->getOperand(i)));
785 }
786 }
787 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000788 }
Chris Lattner6d492922002-08-19 21:32:41 +0000789 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000790
791 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000792 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000793 Out << "((";
794 printType(Out, CPV->getType());
795 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000796 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000797 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
798 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000799 break;
800 }
801 // FALL THROUGH
802 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000803 std::cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000804 abort();
805 }
806}
807
808void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000809 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000810 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000811 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000812 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000813 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000814 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000815 return;
816 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000817
Reid Spencer518310c2004-07-18 00:44:37 +0000818 Constant* CPV = dyn_cast<Constant>(Operand);
819 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +0000820 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000821 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000822 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000823 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000824}
825
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000826void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000827 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000828 Out << "(&"; // Global variables are references as their addresses by llvm
829
830 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000831
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000832 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000833 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000834}
835
Chris Lattner41488192003-06-28 17:15:12 +0000836// generateCompilerSpecificCode - This is where we add conditional compilation
837// directives to cater to specific compilers as need be.
838//
Chris Lattnerc59c1182003-11-16 22:06:14 +0000839static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +0000840 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +0000841 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +0000842 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Reid Spencera8411a62005-01-23 04:32:47 +0000843 << "extern void *_alloca(unsigned long);\n"
844 << "#define alloca(x) _alloca(x)\n"
845 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000846 << "extern void *__builtin_alloca(unsigned long);\n"
847 << "#define alloca(x) __builtin_alloca(x)\n"
Brian Gaekece630052004-12-10 05:44:45 +0000848 << "#elif defined(__sun__)\n"
849 << "#if defined(__sparcv9)\n"
850 << "extern void *__builtin_alloca(unsigned long);\n"
851 << "#else\n"
852 << "extern void *__builtin_alloca(unsigned int);\n"
853 << "#endif\n"
854 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohen3c280bf2006-04-17 17:55:41 +0000855 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +0000856 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +0000857 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000858 << "#include <alloca.h>\n"
859 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +0000860
861 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
862 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +0000863 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +0000864 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +0000865 << "#endif\n\n";
866
867#if 0
868 // At some point, we should support "external weak" vs. "weak" linkages.
869 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
870 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
871 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
872 << "#elif defined(__GNUC__)\n"
873 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
874 << "#else\n"
875 << "#define __EXTERNAL_WEAK__\n"
876 << "#endif\n\n";
877#endif
878
879 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
880 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
881 << "#define __ATTRIBUTE_WEAK__\n"
882 << "#elif defined(__GNUC__)\n"
883 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
884 << "#else\n"
885 << "#define __ATTRIBUTE_WEAK__\n"
886 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000887
888 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
889 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +0000890 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000891 // double __builtin_nan (const char *str)
892 //
893 // This is an implementation of the ISO C99 function nan.
894 //
895 // Since ISO C99 defines this function in terms of strtod, which we do
896 // not implement, a description of the parsing is in order. The string is
897 // parsed as by strtol; that is, the base is recognized by leading 0 or
898 // 0x prefixes. The number parsed is placed in the significand such that
899 // the least significant bit of the number is at the least significant
900 // bit of the significand. The number is truncated to fit the significand
901 // field provided. The significand is forced to be a quiet NaN.
902 //
903 // This function, if given a string literal, is evaluated early enough
904 // that it is considered a compile-time constant.
905 //
906 // float __builtin_nanf (const char *str)
907 //
908 // Similar to __builtin_nan, except the return type is float.
909 //
910 // double __builtin_inf (void)
911 //
912 // Similar to __builtin_huge_val, except a warning is generated if the
913 // target floating-point format does not support infinities. This
914 // function is suitable for implementing the ISO C99 macro INFINITY.
915 //
916 // float __builtin_inff (void)
917 //
918 // Similar to __builtin_inf, except the return type is float.
919 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000920 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
921 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
922 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
923 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
924 << "#define LLVM_INF __builtin_inf() /* Double */\n"
925 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +0000926 << "#define LLVM_PREFETCH(addr,rw,locality) "
927 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000928 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
929 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +0000930 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000931 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +0000932 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
933 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
934 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
935 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
936 << "#define LLVM_INF ((double)0.0) /* Double */\n"
937 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000938 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +0000939 << "#define __ATTRIBUTE_CTOR__\n"
940 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +0000941 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000942 << "#endif\n\n";
943
944 // Output target-specific code that should be inserted into main.
945 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
946 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
947 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
Evan Chenge3db4da2006-06-20 22:11:12 +0000948 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
949 << "defined(__x86_64__)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +0000950 << "#undef CODE_FOR_MAIN\n"
951 << "#define CODE_FOR_MAIN() \\\n"
952 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
953 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
954 << "#endif\n#endif\n";
955
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000956}
957
Chris Lattner9a571ba2006-03-07 22:58:23 +0000958/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
959/// the StaticTors set.
960static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
961 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
962 if (!InitList) return;
963
964 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
965 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
966 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
967
968 if (CS->getOperand(1)->isNullValue())
969 return; // Found a null terminator, exit printing.
970 Constant *FP = CS->getOperand(1);
971 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
972 if (CE->getOpcode() == Instruction::Cast)
973 FP = CE->getOperand(0);
974 if (Function *F = dyn_cast<Function>(FP))
975 StaticTors.insert(F);
976 }
977}
978
979enum SpecialGlobalClass {
980 NotSpecial = 0,
981 GlobalCtors, GlobalDtors,
982 NotPrinted
983};
984
985/// getGlobalVariableClass - If this is a global that is specially recognized
986/// by LLVM, return a code that indicates how we should handle it.
987static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
988 // If this is a global ctors/dtors list, handle it now.
989 if (GV->hasAppendingLinkage() && GV->use_empty()) {
990 if (GV->getName() == "llvm.global_ctors")
991 return GlobalCtors;
992 else if (GV->getName() == "llvm.global_dtors")
993 return GlobalDtors;
994 }
995
996 // Otherwise, it it is other metadata, don't print it. This catches things
997 // like debug information.
998 if (GV->getSection() == "llvm.metadata")
999 return NotPrinted;
1000
1001 return NotSpecial;
1002}
1003
1004
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001005bool CWriter::doInitialization(Module &M) {
1006 // Initialize
1007 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001008
1009 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001010
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001011 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001012 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001013 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001014
Chris Lattner9a571ba2006-03-07 22:58:23 +00001015 // Keep track of which functions are static ctors/dtors so they can have
1016 // an attribute added to their prototypes.
1017 std::set<Function*> StaticCtors, StaticDtors;
1018 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1019 I != E; ++I) {
1020 switch (getGlobalVariableClass(I)) {
1021 default: break;
1022 case GlobalCtors:
1023 FindStaticTors(I, StaticCtors);
1024 break;
1025 case GlobalDtors:
1026 FindStaticTors(I, StaticDtors);
1027 break;
1028 }
1029 }
1030
Chris Lattner16c7bb22002-05-09 02:28:59 +00001031 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001032 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001033 Out << "#include <stdarg.h>\n"; // Varargs support
1034 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001035 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001036
Chris Lattnercf135cb2003-06-02 03:10:53 +00001037 // Provide a definition for `bool' if not compiling with a C++ compiler.
1038 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001039 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001040
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001041 << "\n\n/* Support for floating point constants */\n"
1042 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001043 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001044
Chris Lattnera4d4a852002-08-19 21:48:40 +00001045 << "\n\n/* Global Declarations */\n";
1046
1047 // First output all the declarations for the program, because C requires
1048 // Functions & globals to be declared before they are used.
1049 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001050
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001051 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001052 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001053
Chris Lattnera4d4a852002-08-19 21:48:40 +00001054 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001055 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001056 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001057 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1058 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001059 if (I->hasExternalLinkage()) {
1060 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001061 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001062 Out << ";\n";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001063 } else if (I->hasDLLImportLinkage()) {
1064 Out << "__declspec(dllimport) ";
1065 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1066 Out << ";\n";
1067 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001068 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001069 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001070
Chris Lattnera4d4a852002-08-19 21:48:40 +00001071 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001072 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001073 Out << "double fmod(double, double);\n"; // Support for FP rem
1074 Out << "float fmodf(float, float);\n";
1075
Chris Lattner9a571ba2006-03-07 22:58:23 +00001076 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1077 // Don't print declarations for intrinsic functions.
1078 if (!I->getIntrinsicID() &&
1079 I->getName() != "setjmp" && I->getName() != "longjmp") {
1080 printFunctionSignature(I, true);
1081 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1082 Out << " __ATTRIBUTE_WEAK__";
1083 if (StaticCtors.count(I))
1084 Out << " __ATTRIBUTE_CTOR__";
1085 if (StaticDtors.count(I))
1086 Out << " __ATTRIBUTE_DTOR__";
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001087
1088 if (I->hasName() && I->getName()[0] == 1)
1089 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1090
Chris Lattner9a571ba2006-03-07 22:58:23 +00001091 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001092 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001093 }
1094
Joel Stanley54f60322003-06-25 04:52:09 +00001095 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001096 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001097 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001098 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1099 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001100 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001101 // Ignore special globals, such as debug info.
1102 if (getGlobalVariableClass(I))
1103 continue;
1104
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001105 if (I->hasInternalLinkage())
1106 Out << "static ";
1107 else
1108 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001109 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001110
1111 if (I->hasLinkOnceLinkage())
1112 Out << " __attribute__((common))";
1113 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001114 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001115 Out << ";\n";
1116 }
1117 }
1118
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001119 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001120 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001121 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001122 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1123 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001124 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001125 // Ignore special globals, such as debug info.
1126 if (getGlobalVariableClass(I))
1127 continue;
1128
Chris Lattnere8e035b2002-10-16 20:08:47 +00001129 if (I->hasInternalLinkage())
1130 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001131 else if (I->hasDLLImportLinkage())
1132 Out << "__declspec(dllimport) ";
1133 else if (I->hasDLLExportLinkage())
1134 Out << "__declspec(dllexport) ";
1135
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001136 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001137 if (I->hasLinkOnceLinkage())
1138 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001139 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001140 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001141
1142 // If the initializer is not null, emit the initializer. If it is null,
1143 // we try to avoid emitting large amounts of zeros. The problem with
1144 // this, however, occurs when the variable has weak linkage. In this
1145 // case, the assembler will complain about the variable being both weak
1146 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001147 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001148 Out << " = " ;
1149 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001150 } else if (I->hasWeakLinkage()) {
1151 // We have to specify an initializer, but it doesn't have to be
1152 // complete. If the value is an aggregate, print out { 0 }, and let
1153 // the compiler figure out the rest of the zeros.
1154 Out << " = " ;
1155 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001156 isa<ArrayType>(I->getInitializer()->getType()) ||
1157 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001158 Out << "{ 0 }";
1159 } else {
1160 // Just print it out normally.
1161 writeOperand(I->getInitializer());
1162 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001163 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001164 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001165 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001166 }
1167
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001168 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001169 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001170 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001171}
1172
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001173
Chris Lattner9860e772003-10-12 04:36:29 +00001174/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001175void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001176 // Scan the module for floating point constants. If any FP constant is used
1177 // in the function, we want to redirect it here so that we do not depend on
1178 // the precision of the printed form, unless the printed form preserves
1179 // precision.
1180 //
Chris Lattner68758072004-05-09 06:20:51 +00001181 static unsigned FPCounter = 0;
1182 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1183 I != E; ++I)
1184 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1185 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1186 !FPConstantMap.count(FPC)) {
1187 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001188
Chris Lattner68758072004-05-09 06:20:51 +00001189 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001190
Chris Lattner68758072004-05-09 06:20:51 +00001191 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001192 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001193 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001194 << "ULL; /* " << Val << " */\n";
1195 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001196 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001197 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001198 << "U; /* " << Val << " */\n";
1199 } else
1200 assert(0 && "Unknown float type!");
1201 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001202
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001203 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001204}
Chris Lattner9860e772003-10-12 04:36:29 +00001205
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001206
Chris Lattner2db41cd2002-09-20 15:12:13 +00001207/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001208/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001209///
Chris Lattner68758072004-05-09 06:20:51 +00001210void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001211 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001212 SymbolTable::type_const_iterator I = ST.type_begin();
1213 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001214
1215 // If there are no type names, exit early.
1216 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001217
Chris Lattner58d04d42002-09-20 15:18:30 +00001218 // Print out forward declarations for structure types before anything else!
1219 Out << "/* Structure forward decls */\n";
1220 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001221 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001222 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001223 Out << Name << ";\n";
1224 TypeNames.insert(std::make_pair(STy, Name));
1225 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001226
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001227 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001228
1229 // Now we can print out typedefs...
1230 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001231 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001232 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001233 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001234 Out << "typedef ";
1235 printType(Out, Ty, Name);
1236 Out << ";\n";
1237 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001238
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001239 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001240
Chris Lattner2c601a72002-09-20 15:05:40 +00001241 // Keep track of which structures have been printed so far...
1242 std::set<const StructType *> StructPrinted;
1243
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001244 // Loop over all structures then push them into the stack so they are
1245 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001246 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001247 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001248 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001249 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001250 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001251 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001252}
1253
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001254// Push the struct onto the stack and recursively push all structs
1255// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001256//
1257// TODO: Make this work properly with packed types
1258//
Chris Lattner2c601a72002-09-20 15:05:40 +00001259void CWriter::printContainedStructs(const Type *Ty,
1260 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001261 // Don't walk through pointers.
1262 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1263
1264 // Print all contained types first.
1265 for (Type::subtype_iterator I = Ty->subtype_begin(),
1266 E = Ty->subtype_end(); I != E; ++I)
1267 printContainedStructs(*I, StructPrinted);
1268
Misha Brukmanac25de32003-07-09 17:33:50 +00001269 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001270 // Check to see if we have already printed this struct.
1271 if (StructPrinted.insert(STy).second) {
1272 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001273 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001274 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001275 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001276 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001277 }
1278}
1279
Chris Lattner4cda8352002-08-20 16:55:48 +00001280void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001281 /// isCStructReturn - Should this function actually return a struct by-value?
1282 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1283
Joel Stanley54f60322003-06-25 04:52:09 +00001284 if (F->hasInternalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001285 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1286 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00001287 switch (F->getCallingConv()) {
1288 case CallingConv::X86_StdCall:
1289 Out << "__stdcall ";
1290 break;
1291 case CallingConv::X86_FastCall:
1292 Out << "__fastcall ";
1293 break;
1294 }
1295
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001296 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001297 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001298
1299 std::stringstream FunctionInnards;
1300
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001301 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001302 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001303
Chris Lattner0c54d892006-05-23 23:39:48 +00001304 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001305 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001306 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001307 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1308
1309 // If this is a struct-return function, don't print the hidden
1310 // struct-return argument.
1311 if (isCStructReturn) {
1312 assert(I != E && "Invalid struct return function!");
1313 ++I;
1314 }
1315
Chris Lattneredd8ce12003-05-03 03:14:35 +00001316 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001317 for (; I != E; ++I) {
1318 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001319 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001320 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001321 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001322 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001323 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001324 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001325 }
1326 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001327 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001328 // Loop over the arguments, printing them.
1329 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1330
1331 // If this is a struct-return function, don't print the hidden
1332 // struct-return argument.
1333 if (isCStructReturn) {
1334 assert(I != E && "Invalid struct return function!");
1335 ++I;
1336 }
1337
1338 for (; I != E; ++I) {
1339 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001340 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001341 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001342 }
1343 }
1344
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001345 // Finish printing arguments... if this is a vararg function, print the ...,
1346 // unless there are no known types, in which case, we just emit ().
1347 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001348 if (FT->isVarArg() && PrintedArg) {
1349 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001350 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001351 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001352 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001353 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001354 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001355
1356 // Get the return tpe for the function.
1357 const Type *RetTy;
1358 if (!isCStructReturn)
1359 RetTy = F->getReturnType();
1360 else {
1361 // If this is a struct-return function, print the struct-return type.
1362 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1363 }
1364
1365 // Print out the return type and the signature built above.
1366 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001367}
1368
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001369void CWriter::printFunction(Function &F) {
1370 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001371 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001372
1373 // If this is a struct return function, handle the result with magic.
1374 if (F.getCallingConv() == CallingConv::CSRet) {
1375 const Type *StructTy =
1376 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1377 Out << " ";
1378 printType(Out, StructTy, "StructReturn");
1379 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001380
Chris Lattner0c54d892006-05-23 23:39:48 +00001381 Out << " ";
1382 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1383 Out << " = &StructReturn;\n";
1384 }
1385
1386 bool PrintedVar = false;
1387
Chris Lattner497e19a2002-05-09 20:39:03 +00001388 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001389 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001390 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001391 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001392 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001393 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001394 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001395 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001396 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001397 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001398 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001399
Chris Lattner84e66652003-05-03 07:11:00 +00001400 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1401 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001402 printType(Out, I->getType(),
1403 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001404 Out << ";\n";
1405 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001406 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001407 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001408
Chris Lattner0c54d892006-05-23 23:39:48 +00001409 if (PrintedVar)
1410 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001411
Chris Lattner395fd592004-12-13 21:52:52 +00001412 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001413 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001414
Chris Lattner16c7bb22002-05-09 02:28:59 +00001415 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001416 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001417 if (Loop *L = LI->getLoopFor(BB)) {
1418 if (L->getHeader() == BB && L->getParentLoop() == 0)
1419 printLoop(L);
1420 } else {
1421 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001422 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001423 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001424
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001425 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001426}
1427
Chris Lattnercb3ad012004-05-09 20:41:32 +00001428void CWriter::printLoop(Loop *L) {
1429 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1430 << "' to make GCC happy */\n";
1431 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1432 BasicBlock *BB = L->getBlocks()[i];
1433 Loop *BBLoop = LI->getLoopFor(BB);
1434 if (BBLoop == L)
1435 printBasicBlock(BB);
1436 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001437 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001438 }
1439 Out << " } while (1); /* end of syntactic loop '"
1440 << L->getHeader()->getName() << "' */\n";
1441}
1442
1443void CWriter::printBasicBlock(BasicBlock *BB) {
1444
1445 // Don't print the label for the basic block if there are no uses, or if
1446 // the only terminator use is the predecessor basic block's terminator.
1447 // We have to scan the use list because PHI nodes use basic blocks too but
1448 // do not require a label to be generated.
1449 //
1450 bool NeedsLabel = false;
1451 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1452 if (isGotoCodeNecessary(*PI, BB)) {
1453 NeedsLabel = true;
1454 break;
1455 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001456
Chris Lattnercb3ad012004-05-09 20:41:32 +00001457 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001458
Chris Lattnercb3ad012004-05-09 20:41:32 +00001459 // Output all of the instructions in the basic block...
1460 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1461 ++II) {
1462 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1463 if (II->getType() != Type::VoidTy)
1464 outputLValue(II);
1465 else
1466 Out << " ";
1467 visit(*II);
1468 Out << ";\n";
1469 }
1470 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001471
Chris Lattnercb3ad012004-05-09 20:41:32 +00001472 // Don't emit prefix or suffix for the terminator...
1473 visit(*BB->getTerminator());
1474}
1475
1476
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001477// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001478// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001479//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001480void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001481 // If this is a struct return function, return the temporary struct.
1482 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1483 Out << " return StructReturn;\n";
1484 return;
1485 }
1486
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001487 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001488 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001489 &*--I.getParent()->getParent()->end() == I.getParent() &&
1490 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001491 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001492 }
Chris Lattner44408262002-05-09 03:50:42 +00001493
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001494 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001495 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001496 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001497 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001498 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001499 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001500}
1501
Chris Lattnera9f5e052003-04-22 20:19:52 +00001502void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001503
Chris Lattnera9f5e052003-04-22 20:19:52 +00001504 Out << " switch (";
1505 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001506 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001507 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001508 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001509 Out << ";\n";
1510 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1511 Out << " case ";
1512 writeOperand(SI.getOperand(i));
1513 Out << ":\n";
1514 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001515 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001516 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001517 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001518 Out << " break;\n";
1519 }
1520 Out << " }\n";
1521}
1522
Chris Lattnera9d12c02004-10-16 18:12:13 +00001523void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001524 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001525}
1526
Chris Lattnercb3ad012004-05-09 20:41:32 +00001527bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1528 /// FIXME: This should be reenabled, but loop reordering safe!!
1529 return true;
1530
Chris Lattner67c2d182005-03-18 16:12:37 +00001531 if (next(Function::iterator(From)) != Function::iterator(To))
1532 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001533
1534 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001535
Chris Lattnercb3ad012004-05-09 20:41:32 +00001536 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001537 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001538 return false;
1539}
1540
John Criswell57bbfce2004-10-20 14:38:39 +00001541void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001542 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001543 unsigned Indent) {
1544 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1545 PHINode *PN = cast<PHINode>(I);
1546 // Now we have to do the printing.
1547 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1548 if (!isa<UndefValue>(IV)) {
1549 Out << std::string(Indent, ' ');
1550 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1551 writeOperand(IV);
1552 Out << "; /* for PHI node */\n";
1553 }
1554 }
1555}
1556
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001557void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001558 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001559 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001560 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001561 writeOperand(Succ);
1562 Out << ";\n";
1563 }
1564}
1565
Misha Brukman37f92e22003-09-11 22:34:13 +00001566// Branch instruction printing - Avoid printing out a branch to a basic block
1567// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001568//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001569void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001570
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001571 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001572 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001573 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001574 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001575 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001576
John Criswell57bbfce2004-10-20 14:38:39 +00001577 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001578 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001579
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001580 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001581 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001582 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001583 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001584 }
1585 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001586 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001587 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001588 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001589 Out << ") {\n";
1590
John Criswell57bbfce2004-10-20 14:38:39 +00001591 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001592 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001593 }
1594
1595 Out << " }\n";
1596 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001597 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001598 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001599 }
1600 Out << "\n";
1601}
1602
Chris Lattner84e66652003-05-03 07:11:00 +00001603// PHI nodes get copied into temporary values at the end of predecessor basic
1604// blocks. We now need to copy these temporary values into the REAL value for
1605// the PHI.
1606void CWriter::visitPHINode(PHINode &I) {
1607 writeOperand(&I);
1608 Out << "__PHI_TEMPORARY";
1609}
1610
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001611
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001612void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001613 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001614 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001615
1616 // We must cast the results of binary operations which might be promoted.
1617 bool needsCast = false;
1618 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001619 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1620 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001621 needsCast = true;
1622 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001623 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001624 Out << ")(";
1625 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001626
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001627 // If this is a negation operation, print it out as such. For FP, we don't
1628 // want to print "-0.0 - X".
1629 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001630 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001631 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001632 Out << ")";
Chris Lattner57da2522005-08-23 20:22:50 +00001633 } else if (I.getOpcode() == Instruction::Rem &&
1634 I.getType()->isFloatingPoint()) {
1635 // Output a call to fmod/fmodf instead of emitting a%b
1636 if (I.getType() == Type::FloatTy)
1637 Out << "fmodf(";
1638 else
1639 Out << "fmod(";
1640 writeOperand(I.getOperand(0));
1641 Out << ", ";
1642 writeOperand(I.getOperand(1));
1643 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001644 } else {
1645 writeOperand(I.getOperand(0));
1646
1647 switch (I.getOpcode()) {
1648 case Instruction::Add: Out << " + "; break;
1649 case Instruction::Sub: Out << " - "; break;
1650 case Instruction::Mul: Out << '*'; break;
1651 case Instruction::Div: Out << '/'; break;
1652 case Instruction::Rem: Out << '%'; break;
1653 case Instruction::And: Out << " & "; break;
1654 case Instruction::Or: Out << " | "; break;
1655 case Instruction::Xor: Out << " ^ "; break;
1656 case Instruction::SetEQ: Out << " == "; break;
1657 case Instruction::SetNE: Out << " != "; break;
1658 case Instruction::SetLE: Out << " <= "; break;
1659 case Instruction::SetGE: Out << " >= "; break;
1660 case Instruction::SetLT: Out << " < "; break;
1661 case Instruction::SetGT: Out << " > "; break;
1662 case Instruction::Shl : Out << " << "; break;
1663 case Instruction::Shr : Out << " >> "; break;
1664 default: std::cerr << "Invalid operator type!" << I; abort();
1665 }
1666
1667 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001668 }
1669
Brian Gaeke031a1122003-06-23 20:00:51 +00001670 if (needsCast) {
1671 Out << "))";
1672 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001673}
1674
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001675void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001676 if (I.getType() == Type::BoolTy) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001677 Out << '(';
Chris Lattnerd13bd222003-06-01 03:36:51 +00001678 writeOperand(I.getOperand(0));
1679 Out << " != 0)";
1680 return;
1681 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001682 Out << '(';
Chris Lattner7635ea42003-11-03 01:01:59 +00001683 printType(Out, I.getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001684 Out << ')';
Chris Lattnerf5612b762003-04-23 19:09:22 +00001685 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1686 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1687 // Avoid "cast to pointer from integer of different size" warnings
Misha Brukmand6a29a52005-04-20 16:05:03 +00001688 Out << "(long)";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001689 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001690
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001691 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001692}
1693
Chris Lattner9f24a072004-03-12 05:52:14 +00001694void CWriter::visitSelectInst(SelectInst &I) {
1695 Out << "((";
1696 writeOperand(I.getCondition());
1697 Out << ") ? (";
1698 writeOperand(I.getTrueValue());
1699 Out << ") : (";
1700 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001701 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00001702}
1703
1704
Chris Lattnerc2421432004-05-09 04:30:20 +00001705void CWriter::lowerIntrinsics(Function &F) {
1706 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1707 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1708 if (CallInst *CI = dyn_cast<CallInst>(I++))
1709 if (Function *F = CI->getCalledFunction())
1710 switch (F->getIntrinsicID()) {
1711 case Intrinsic::not_intrinsic:
1712 case Intrinsic::vastart:
1713 case Intrinsic::vacopy:
1714 case Intrinsic::vaend:
1715 case Intrinsic::returnaddress:
1716 case Intrinsic::frameaddress:
1717 case Intrinsic::setjmp:
1718 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00001719 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00001720 case Intrinsic::dbg_stoppoint:
Chris Lattner1e142892006-09-09 06:17:12 +00001721 case Intrinsic::powi_f32:
1722 case Intrinsic::powi_f64:
Chris Lattnerc2421432004-05-09 04:30:20 +00001723 // We directly implement these intrinsics
1724 break;
1725 default:
Chris Lattner87242152006-03-13 23:09:05 +00001726 // If this is an intrinsic that directly corresponds to a GCC
1727 // builtin, we handle it.
1728 const char *BuiltinName = "";
1729#define GET_GCC_BUILTIN_NAME
1730#include "llvm/Intrinsics.gen"
1731#undef GET_GCC_BUILTIN_NAME
1732 // If we handle it, don't lower it.
1733 if (BuiltinName[0]) break;
1734
Chris Lattnerc2421432004-05-09 04:30:20 +00001735 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00001736 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001737 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00001738 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00001739
Chris Lattnerc2421432004-05-09 04:30:20 +00001740 IL.LowerIntrinsicCall(CI);
1741 if (Before) { // Move iterator to instruction after call
1742 I = Before; ++I;
1743 } else {
1744 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00001745 }
Chris Lattner87242152006-03-13 23:09:05 +00001746 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00001747 }
Chris Lattner4ef51372004-02-14 00:31:10 +00001748}
1749
1750
1751
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001752void CWriter::visitCallInst(CallInst &I) {
Chris Lattner87242152006-03-13 23:09:05 +00001753 bool WroteCallee = false;
1754
Chris Lattner18ac3c82003-05-08 18:41:45 +00001755 // Handle intrinsic function calls first...
1756 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00001757 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001758 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00001759 default: {
1760 // If this is an intrinsic that directly corresponds to a GCC
1761 // builtin, we emit it here.
1762 const char *BuiltinName = "";
1763#define GET_GCC_BUILTIN_NAME
1764#include "llvm/Intrinsics.gen"
1765#undef GET_GCC_BUILTIN_NAME
1766 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1767
1768 Out << BuiltinName;
1769 WroteCallee = true;
1770 break;
1771 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001772 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00001773 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001774
Andrew Lenharth558bc882005-06-18 18:34:52 +00001775 Out << "va_start(*(va_list*)";
1776 writeOperand(I.getOperand(1));
1777 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001778 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001779 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00001780 std::cerr << "The C backend does not currently support zero "
1781 << "argument varargs functions, such as '"
1782 << I.getParent()->getParent()->getName() << "'!\n";
1783 abort();
1784 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00001785 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001786 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001787 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001788 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001789 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00001790 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001791 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001792 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00001793 } else {
1794 Out << "va_end(*(va_list*)0)";
1795 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001796 return;
Chris Lattner317201d2004-03-13 00:24:00 +00001797 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00001798 Out << "0; ";
1799 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001800 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00001801 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00001802 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001803 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00001804 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001805 case Intrinsic::returnaddress:
1806 Out << "__builtin_return_address(";
1807 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001808 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001809 return;
1810 case Intrinsic::frameaddress:
1811 Out << "__builtin_frame_address(";
1812 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001813 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00001814 return;
Chris Lattner1e142892006-09-09 06:17:12 +00001815 case Intrinsic::powi_f32:
1816 case Intrinsic::powi_f64:
1817 Out << "__builtin_powi(";
1818 writeOperand(I.getOperand(1));
1819 Out << ", ";
1820 writeOperand(I.getOperand(2));
1821 Out << ')';
1822 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00001823 case Intrinsic::setjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00001824#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1825 Out << "_"; // Use _setjmp on systems that support it!
1826#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00001827 Out << "setjmp(*(jmp_buf*)";
1828 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001829 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001830 return;
1831 case Intrinsic::longjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00001832#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1833 Out << "_"; // Use _longjmp on systems that support it!
1834#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00001835 Out << "longjmp(*(jmp_buf*)";
1836 writeOperand(I.getOperand(1));
1837 Out << ", ";
1838 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001839 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00001840 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00001841 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00001842 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00001843 writeOperand(I.getOperand(1));
1844 Out << ", ";
1845 writeOperand(I.getOperand(2));
1846 Out << ", ";
1847 writeOperand(I.getOperand(3));
1848 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00001849 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00001850 case Intrinsic::dbg_stoppoint: {
1851 // If we use writeOperand directly we get a "u" suffix which is rejected
1852 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00001853 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00001854
1855 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00001856 << SPI.getLine()
1857 << " \"" << SPI.getDirectory()
1858 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00001859 return;
1860 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00001861 }
1862 }
1863
Chris Lattner4394d512004-11-13 22:21:56 +00001864 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001865
Chris Lattner0c54d892006-05-23 23:39:48 +00001866 // If this is a call to a struct-return function, assign to the first
1867 // parameter instead of passing it to the call.
1868 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
1869 if (isStructRet) {
1870 Out << "*(";
1871 writeOperand(I.getOperand(1));
1872 Out << ") = ";
1873 }
1874
Chris Lattnerfe673d92005-05-06 06:53:07 +00001875 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00001876
1877 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001878 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00001879
1880 if (!WroteCallee) {
1881 // If this is an indirect call to a struct return function, we need to cast
1882 // the pointer.
1883 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001884
Chris Lattner0c54d892006-05-23 23:39:48 +00001885 // GCC is a real PITA. It does not permit codegening casts of functions to
1886 // function pointers if they are in a call (it generates a trap instruction
1887 // instead!). We work around this by inserting a cast to void* in between
1888 // the function and the function pointer cast. Unfortunately, we can't just
1889 // form the constant expression here, because the folder will immediately
1890 // nuke it.
1891 //
1892 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1893 // that void* and function pointers have the same size. :( To deal with this
1894 // in the common case, we handle casts where the number of arguments passed
1895 // match exactly.
1896 //
1897 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1898 if (CE->getOpcode() == Instruction::Cast)
1899 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1900 NeedsCast = true;
1901 Callee = RF;
1902 }
1903
1904 if (NeedsCast) {
1905 // Ok, just cast the pointer type.
1906 Out << "((";
1907 if (!isStructRet)
1908 printType(Out, I.getCalledValue()->getType());
1909 else
1910 printStructReturnPointerFunctionType(Out,
1911 cast<PointerType>(I.getCalledValue()->getType()));
1912 Out << ")(void*)";
1913 }
1914 writeOperand(Callee);
1915 if (NeedsCast) Out << ')';
1916 }
1917
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001918 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001919
Chris Lattner4394d512004-11-13 22:21:56 +00001920 unsigned NumDeclaredParams = FTy->getNumParams();
1921
Chris Lattner0c54d892006-05-23 23:39:48 +00001922 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1923 unsigned ArgNo = 0;
1924 if (isStructRet) { // Skip struct return argument.
1925 ++AI;
1926 ++ArgNo;
1927 }
1928
1929 bool PrintedArg = false;
1930 for (; AI != AE; ++AI, ++ArgNo) {
1931 if (PrintedArg) Out << ", ";
1932 if (ArgNo < NumDeclaredParams &&
1933 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001934 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00001935 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001936 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00001937 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001938 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00001939 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001940 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001941 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001942}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001943
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001944void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001945 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001946}
1947
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001948void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001949 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001950 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001951 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001952 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001953 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001954 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001955 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001956 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001957 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001958 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001959}
1960
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001961void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00001962 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001963}
1964
Chris Lattner23e90702003-11-25 20:49:55 +00001965void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1966 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001967 bool HasImplicitAddress = false;
1968 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1969 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1970 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001971 } else if (isDirectAlloca(Ptr)) {
1972 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001973 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001974
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001975 if (I == E) {
1976 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001977 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001978
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001979 writeOperandInternal(Ptr);
1980 return;
1981 }
1982
Chris Lattner23e90702003-11-25 20:49:55 +00001983 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001984 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1985 Out << "(&";
1986
1987 writeOperandInternal(Ptr);
1988
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001989 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001990 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001991 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1992 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001993
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001994 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1995 "Can only have implicit address with direct accessing");
1996
1997 if (HasImplicitAddress) {
1998 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00001999 } else if (CI && CI->isNullValue()) {
2000 gep_type_iterator TmpI = I; ++TmpI;
2001
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002002 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00002003 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002004 Out << (HasImplicitAddress ? "." : "->");
Chris Lattnerbc771c52003-11-25 23:44:40 +00002005 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
Chris Lattner23e90702003-11-25 20:49:55 +00002006 I = ++TmpI;
2007 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002008 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002009
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002010 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00002011 if (isa<StructType>(*I)) {
2012 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002013 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002014 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00002015 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002016 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002017 }
2018}
2019
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002020void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002021 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002022 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002023 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002024 printType(Out, I.getType(), "volatile*");
2025 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002026 }
2027
Chris Lattner5dfe7672002-08-22 22:48:55 +00002028 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00002029
2030 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00002031 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002032}
2033
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002034void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002035 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002036 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002037 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002038 printType(Out, I.getOperand(0)->getType(), " volatile*");
2039 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002040 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002041 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00002042 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002043 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002044 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002045}
2046
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002047void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002048 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002049 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2050 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002051}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002052
Chris Lattner4d45bd02003-10-18 05:57:43 +00002053void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002054 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002055 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002056 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002057 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002058 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002059}
2060
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002061//===----------------------------------------------------------------------===//
2062// External Interface declaration
2063//===----------------------------------------------------------------------===//
2064
Chris Lattner1911fd42006-09-04 04:14:57 +00002065bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2066 std::ostream &o,
2067 CodeGenFileType FileType,
2068 bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002069 if (FileType != TargetMachine::AssemblyFile) return true;
2070
Chris Lattner99c59e82004-05-23 21:23:35 +00002071 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002072 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002073 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002074 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002075 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002076 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002077 return false;
2078}