blob: 99f95ba913b88e5263fea01ac531daf6a294e4f8 [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"
Andrew Lenharth29c277f2006-11-27 23:50:49 +000026#include "llvm/InlineAsm.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000027#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000028#include "llvm/Analysis/FindUsedTypes.h"
29#include "llvm/Analysis/LoopInfo.h"
Chris Lattner30483732004-06-20 07:49:54 +000030#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000031#include "llvm/Transforms/Scalar.h"
Chris Lattnerd36c9702004-07-11 02:48:49 +000032#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000033#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000034#include "llvm/Support/CFG.h"
Chris Lattner23e90702003-11-25 20:49:55 +000035#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000036#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000037#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000038#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/StringExtras.h"
Chris Lattner67c2d182005-03-18 16:12:37 +000040#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/Support/MathExtras.h"
42#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000043#include <algorithm>
Reid Spencer954da372004-07-04 12:19:56 +000044#include <iostream>
Duraid Madinad2dec7d2005-12-27 10:40:34 +000045#include <ios>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000046#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000049namespace {
Chris Lattnerd36c9702004-07-11 02:48:49 +000050 // Register the target.
Chris Lattner71d24aa2004-07-11 03:27:42 +000051 RegisterTarget<CTargetMachine> X("c", " C backend");
Chris Lattnerd36c9702004-07-11 02:48:49 +000052
Chris Lattnerf9a05322006-02-13 22:22:42 +000053 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
54 /// any unnamed structure types that are used by the program, and merges
55 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000056 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000057 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Chris Lattner68758072004-05-09 06:20:51 +000058 void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<FindUsedTypes>();
60 }
61
62 virtual const char *getPassName() const {
63 return "C backend type canonicalizer";
64 }
65
Chris Lattnerb12914b2004-09-20 04:48:05 +000066 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000067 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000068
Chris Lattner68758072004-05-09 06:20:51 +000069 /// CWriter - This class is the main chunk of code that converts an LLVM
70 /// module to a C translation unit.
71 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
Misha Brukmand6a29a52005-04-20 16:05:03 +000072 std::ostream &Out;
Chris Lattnerb71fd782006-11-15 18:00:10 +000073 IntrinsicLowering IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000074 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000075 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000076 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000077 std::map<const Type *, std::string> TypeNames;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000078
Chris Lattneredd8ce12003-05-03 03:14:35 +000079 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000080 public:
Chris Lattnerbc641b92006-03-23 05:43:16 +000081 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000082
Chris Lattner94f4f8e2004-02-13 23:00:29 +000083 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000084
Chris Lattnercb3ad012004-05-09 20:41:32 +000085 void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<LoopInfo>();
87 AU.setPreservesAll();
88 }
89
Chris Lattner68758072004-05-09 06:20:51 +000090 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000091
Chris Lattner68758072004-05-09 06:20:51 +000092 bool runOnFunction(Function &F) {
Chris Lattnercb3ad012004-05-09 20:41:32 +000093 LI = &getAnalysis<LoopInfo>();
94
Chris Lattner3150e2d2004-12-05 06:49:44 +000095 // Get rid of intrinsics we can't handle.
96 lowerIntrinsics(F);
97
Chris Lattner68758072004-05-09 06:20:51 +000098 // Output all floating point constants that cannot be printed accurately.
99 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000100
101 // Ensure that no local symbols conflict with global symbols.
102 F.renameLocalSymbols();
103
Chris Lattner68758072004-05-09 06:20:51 +0000104 printFunction(F);
105 FPConstantMap.clear();
106 return false;
107 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000108
Chris Lattner68758072004-05-09 06:20:51 +0000109 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000110 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000111 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000112 TypeNames.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000113 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000114 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000115
Chris Lattneredd8ce12003-05-03 03:14:35 +0000116 std::ostream &printType(std::ostream &Out, const Type *Ty,
117 const std::string &VariableName = "",
Chris Lattner7635ea42003-11-03 01:01:59 +0000118 bool IgnoreName = false);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000119
Chris Lattner0c54d892006-05-23 23:39:48 +0000120 void printStructReturnPointerFunctionType(std::ostream &Out,
121 const PointerType *Ty);
122
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000123 void writeOperand(Value *Operand);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000124 void writeOperandRaw(Value *Operand);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000125 void writeOperandInternal(Value *Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +0000126 void writeOperandWithCast(Value* Operand, unsigned Opcode);
127 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000128
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000129 private :
Chris Lattnerc2421432004-05-09 04:30:20 +0000130 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000131
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000132 void printModule(Module *M);
Chris Lattner68758072004-05-09 06:20:51 +0000133 void printModuleTypes(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +0000134 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000135 void printFloatingPointConstants(Function &F);
Chris Lattner4cda8352002-08-20 16:55:48 +0000136 void printFunctionSignature(const Function *F, bool Prototype);
137
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000138 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000139 void printBasicBlock(BasicBlock *BB);
140 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000141
Reid Spencer3da59db2006-11-27 01:05:10 +0000142 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Chris Lattner6d492922002-08-19 21:32:41 +0000143 void printConstant(Constant *CPV);
Reid Spencer1628cec2006-10-26 06:15:43 +0000144 void printConstantWithCast(Constant *CPV, unsigned Opcode);
145 bool printConstExprCast(const ConstantExpr *CE);
Chris Lattner6d492922002-08-19 21:32:41 +0000146 void printConstantArray(ConstantArray *CPA);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000147 void printConstantPacked(ConstantPacked *CP);
Chris Lattner6d492922002-08-19 21:32:41 +0000148
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000149 // isInlinableInst - Attempt to inline instructions into their uses to build
150 // trees as much as possible. To do this, we have to consistently decide
151 // what is acceptable to inline, so that variable declarations don't get
152 // printed and an extra copy of the expr is not emitted.
153 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000154 static bool isInlinableInst(const Instruction &I) {
Chris Lattner433e25a2004-05-20 20:25:50 +0000155 // Always inline setcc instructions, even if they are shared by multiple
156 // expressions. GCC generates horrible code if we don't.
157 if (isa<SetCondInst>(I)) return true;
158
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000159 // Must be an expression, must be used exactly once. If it is dead, we
160 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +0000161 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000162 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Andrew Lenharth558bc882005-06-18 18:34:52 +0000163 isa<LoadInst>(I) || isa<VAArgInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000164 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000165 return false;
166
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000167 // Must not be used in inline asm
168 if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
169
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000170 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000171 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000172 }
173
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000174 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
175 // variables which are accessed with the & operator. This causes GCC to
176 // generate significantly better code than to emit alloca calls directly.
177 //
178 static const AllocaInst *isDirectAlloca(const Value *V) {
179 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
180 if (!AI) return false;
181 if (AI->isArrayAllocation())
182 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000183 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000184 return 0;
185 return AI;
186 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000187
188 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
189 static bool isInlineAsm(const Instruction& I) {
190 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
191 return true;
192 return false;
193 }
194
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000195 // Instruction visitation functions
196 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000197
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000198 void visitReturnInst(ReturnInst &I);
199 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000200 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000201 void visitInvokeInst(InvokeInst &I) {
202 assert(0 && "Lowerinvoke pass didn't work!");
203 }
204
205 void visitUnwindInst(UnwindInst &I) {
206 assert(0 && "Lowerinvoke pass didn't work!");
207 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000208 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000209
Chris Lattner84e66652003-05-03 07:11:00 +0000210 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000211 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000212
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000213 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000214 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000215 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000216 void visitInlineAsm(CallInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000217 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000218
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000219 void visitMallocInst(MallocInst &I);
220 void visitAllocaInst(AllocaInst &I);
221 void visitFreeInst (FreeInst &I);
222 void visitLoadInst (LoadInst &I);
223 void visitStoreInst (StoreInst &I);
224 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000225 void visitVAArgInst (VAArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000226
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000227 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000228 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000229 abort();
230 }
231
232 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000233 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000234 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000235
236 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000237 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
238 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000239 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
240 unsigned Indent);
Chris Lattner23e90702003-11-25 20:49:55 +0000241 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
242 gep_type_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000243 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000244}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000245
Chris Lattner68758072004-05-09 06:20:51 +0000246/// This method inserts names for any unnamed structure types that are used by
247/// the program, and removes names from structure types that are not used by the
248/// program.
249///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000250bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000251 // Get a set of types that are used by the program...
252 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000253
Chris Lattner68758072004-05-09 06:20:51 +0000254 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000255 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000256 //
257 SymbolTable &MST = M.getSymbolTable();
Reid Spencer9231ac82004-05-25 08:53:40 +0000258 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
259 TI != TE; ) {
260 SymbolTable::type_iterator I = TI++;
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000261
262 // If this is not used, remove it from the symbol table.
263 std::set<const Type *>::iterator UTI = UT.find(I->second);
264 if (UTI == UT.end())
265 MST.remove(I);
266 else
267 UT.erase(UTI); // Only keep one name for this type.
Reid Spencer9231ac82004-05-25 08:53:40 +0000268 }
Chris Lattner68758072004-05-09 06:20:51 +0000269
270 // UT now contains types that are not named. Loop over it, naming
271 // structure types.
272 //
273 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000274 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000275 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
276 I != E; ++I)
277 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner9d1af972004-05-28 05:47:27 +0000278 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
279 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000280 Changed = true;
281 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000282
283
284 // Loop over all external functions and globals. If we have two with
285 // identical names, merge them.
286 // FIXME: This code should disappear when we don't allow values with the same
287 // names when they have different types!
288 std::map<std::string, GlobalValue*> ExtSymbols;
289 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
290 Function *GV = I++;
291 if (GV->isExternal() && GV->hasName()) {
292 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
293 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
294 if (!X.second) {
295 // Found a conflict, replace this global with the previous one.
296 GlobalValue *OldGV = X.first->second;
297 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
298 GV->eraseFromParent();
299 Changed = true;
300 }
301 }
302 }
303 // Do the same for globals.
304 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
305 I != E;) {
306 GlobalVariable *GV = I++;
307 if (GV->isExternal() && GV->hasName()) {
308 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
309 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
310 if (!X.second) {
311 // Found a conflict, replace this global with the previous one.
312 GlobalValue *OldGV = X.first->second;
313 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
314 GV->eraseFromParent();
315 Changed = true;
316 }
317 }
318 }
319
Chris Lattner68758072004-05-09 06:20:51 +0000320 return Changed;
321}
322
Chris Lattner0c54d892006-05-23 23:39:48 +0000323/// printStructReturnPointerFunctionType - This is like printType for a struct
324/// return type, except, instead of printing the type as void (*)(Struct*, ...)
325/// print it as "Struct (*)(...)", for struct return functions.
326void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
327 const PointerType *TheTy) {
328 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
329 std::stringstream FunctionInnards;
330 FunctionInnards << " (*) (";
331 bool PrintedType = false;
332
333 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
334 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
335 for (++I; I != E; ++I) {
336 if (PrintedType)
337 FunctionInnards << ", ";
338 printType(FunctionInnards, *I, "");
339 PrintedType = true;
340 }
341 if (FTy->isVarArg()) {
342 if (PrintedType)
343 FunctionInnards << ", ...";
344 } else if (!PrintedType) {
345 FunctionInnards << "void";
346 }
347 FunctionInnards << ')';
348 std::string tstr = FunctionInnards.str();
349 printType(Out, RetTy, tstr);
350}
351
Chris Lattner68758072004-05-09 06:20:51 +0000352
Chris Lattner83c57752002-08-19 22:17:53 +0000353// Pass the Type* and the variable name and this prints out the variable
354// declaration.
355//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000356std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
357 const std::string &NameSoFar,
Chris Lattner7635ea42003-11-03 01:01:59 +0000358 bool IgnoreName) {
Chris Lattner83c57752002-08-19 22:17:53 +0000359 if (Ty->isPrimitiveType())
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000360 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000361 case Type::VoidTyID: return Out << "void " << NameSoFar;
362 case Type::BoolTyID: return Out << "bool " << NameSoFar;
363 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
364 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
365 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
366 case Type::ShortTyID: return Out << "short " << NameSoFar;
367 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
368 case Type::IntTyID: return Out << "int " << NameSoFar;
369 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
370 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
371 case Type::FloatTyID: return Out << "float " << NameSoFar;
372 case Type::DoubleTyID: return Out << "double " << NameSoFar;
373 default :
Chris Lattner76e2df22004-07-15 02:14:30 +0000374 std::cerr << "Unknown primitive type: " << *Ty << "\n";
Chris Lattner83c57752002-08-19 22:17:53 +0000375 abort();
376 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000377
Chris Lattner83c57752002-08-19 22:17:53 +0000378 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000379 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000380 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000381 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000382 }
Chris Lattner83c57752002-08-19 22:17:53 +0000383
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000384 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000385 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000386 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000387 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000388 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner0c54d892006-05-23 23:39:48 +0000389 for (FunctionType::param_iterator I = FTy->param_begin(),
390 E = FTy->param_end(); I != E; ++I) {
391 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000392 FunctionInnards << ", ";
393 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000394 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000395 if (FTy->isVarArg()) {
396 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000397 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000398 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000399 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000400 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000401 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000402 std::string tstr = FunctionInnards.str();
Chris Lattner0c54d892006-05-23 23:39:48 +0000403 printType(Out, FTy->getReturnType(), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000404 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000405 }
406 case Type::StructTyID: {
407 const StructType *STy = cast<StructType>(Ty);
408 Out << NameSoFar + " {\n";
409 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000410 for (StructType::element_iterator I = STy->element_begin(),
411 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000412 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000413 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000414 Out << ";\n";
415 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000416 return Out << '}';
Misha Brukmand6a29a52005-04-20 16:05:03 +0000417 }
Chris Lattner83c57752002-08-19 22:17:53 +0000418
419 case Type::PointerTyID: {
420 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000421 std::string ptrName = "*" + NameSoFar;
422
Robert Bocchinob78e8382006-01-20 20:43:57 +0000423 if (isa<ArrayType>(PTy->getElementType()) ||
424 isa<PackedType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000425 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000426
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000427 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000428 }
Chris Lattner83c57752002-08-19 22:17:53 +0000429
430 case Type::ArrayTyID: {
431 const ArrayType *ATy = cast<ArrayType>(Ty);
432 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000433 if (NumElements == 0) NumElements = 1;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000434 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000435 NameSoFar + "[" + utostr(NumElements) + "]");
436 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000437
Robert Bocchinob78e8382006-01-20 20:43:57 +0000438 case Type::PackedTyID: {
439 const PackedType *PTy = cast<PackedType>(Ty);
440 unsigned NumElements = PTy->getNumElements();
441 if (NumElements == 0) NumElements = 1;
442 return printType(Out, PTy->getElementType(),
443 NameSoFar + "[" + utostr(NumElements) + "]");
444 }
445
Chris Lattner04b72c82002-10-16 00:08:22 +0000446 case Type::OpaqueTyID: {
447 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000448 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000449 assert(TypeNames.find(Ty) == TypeNames.end());
450 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000451 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000452 }
Chris Lattner83c57752002-08-19 22:17:53 +0000453 default:
454 assert(0 && "Unhandled case in getTypeProps!");
455 abort();
456 }
457
458 return Out;
459}
460
Chris Lattner6d492922002-08-19 21:32:41 +0000461void CWriter::printConstantArray(ConstantArray *CPA) {
462
463 // As a special case, print the array as a string if it is an array of
464 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000465 //
Chris Lattner6d492922002-08-19 21:32:41 +0000466 const Type *ETy = CPA->getType()->getElementType();
467 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
468
469 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000470 if (isString && (CPA->getNumOperands() == 0 ||
471 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000472 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000473
Chris Lattner6d492922002-08-19 21:32:41 +0000474 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000475 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000476 // Keep track of whether the last number was a hexadecimal escape
477 bool LastWasHex = false;
478
Chris Lattner6d492922002-08-19 21:32:41 +0000479 // Do not include the last character, which we know is null
480 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000481 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000482
Chris Lattner02da6c02003-06-16 12:09:09 +0000483 // Print it out literally if it is a printable character. The only thing
484 // to be careful about is when the last letter output was a hex escape
485 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000486 // explicitly (the C compiler thinks it is a continuation of the previous
487 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000488 //
489 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
490 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000491 if (C == '"' || C == '\\')
492 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000493 else
494 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000495 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000496 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000497 switch (C) {
498 case '\n': Out << "\\n"; break;
499 case '\t': Out << "\\t"; break;
500 case '\r': Out << "\\r"; break;
501 case '\v': Out << "\\v"; break;
502 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000503 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000504 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000505 default:
506 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000507 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
508 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
509 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000510 break;
511 }
512 }
513 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000514 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000515 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000516 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000517 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000518 Out << ' ';
Chris Lattner6d492922002-08-19 21:32:41 +0000519 printConstant(cast<Constant>(CPA->getOperand(0)));
520 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
521 Out << ", ";
522 printConstant(cast<Constant>(CPA->getOperand(i)));
523 }
524 }
525 Out << " }";
526 }
527}
528
Robert Bocchinob78e8382006-01-20 20:43:57 +0000529void CWriter::printConstantPacked(ConstantPacked *CP) {
530 Out << '{';
531 if (CP->getNumOperands()) {
532 Out << ' ';
533 printConstant(cast<Constant>(CP->getOperand(0)));
534 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
535 Out << ", ";
536 printConstant(cast<Constant>(CP->getOperand(i)));
537 }
538 }
539 Out << " }";
540}
541
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000542// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
543// textually as a double (rather than as a reference to a stack-allocated
544// variable). We decide this by converting CFP to a string and back into a
545// double, and then checking whether the conversion results in a bit-equal
546// double to the original value of CFP. This depends on us and the target C
547// compiler agreeing on the conversion process (which is pretty likely since we
548// only deal in IEEE FP).
549//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000550static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Reid Spencerbcf81242006-11-05 19:26:37 +0000551#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000552 char Buffer[100];
553 sprintf(Buffer, "%a", CFP->getValue());
554
555 if (!strncmp(Buffer, "0x", 2) ||
556 !strncmp(Buffer, "-0x", 3) ||
557 !strncmp(Buffer, "+0x", 3))
558 return atof(Buffer) == CFP->getValue();
559 return false;
560#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000561 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000562
563 while (StrVal[0] == ' ')
564 StrVal.erase(StrVal.begin());
565
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000566 // Check to make sure that the stringized number is not some string like "Inf"
567 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000568 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
569 ((StrVal[0] == '-' || StrVal[0] == '+') &&
570 (StrVal[1] >= '0' && StrVal[1] <= '9')))
571 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000572 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000573 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000574#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000575}
Chris Lattner6d492922002-08-19 21:32:41 +0000576
Reid Spencer3da59db2006-11-27 01:05:10 +0000577/// Print out the casting for a cast operation. This does the double casting
578/// necessary for conversion to the destination type, if necessary.
579/// @returns true if a closing paren is necessary
580/// @brief Print a cast
581void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
582 Out << '(';
583 printType(Out, DstTy);
584 Out << ')';
585 switch (opc) {
586 case Instruction::UIToFP:
587 case Instruction::ZExt:
588 if (SrcTy->isSigned()) {
589 Out << '(';
590 printType(Out, SrcTy->getUnsignedVersion());
591 Out << ')';
592 }
593 break;
594 case Instruction::SIToFP:
595 case Instruction::SExt:
596 if (SrcTy->isUnsigned()) {
597 Out << '(';
598 printType(Out, SrcTy->getSignedVersion());
599 Out << ')';
600 }
601 break;
602 case Instruction::IntToPtr:
603 case Instruction::PtrToInt:
604 // Avoid "cast to pointer from integer of different size" warnings
605 Out << "(unsigned long)";
606 break;
607 case Instruction::Trunc:
608 case Instruction::BitCast:
609 case Instruction::FPExt:
610 case Instruction::FPTrunc:
611 case Instruction::FPToSI:
612 case Instruction::FPToUI:
613 default:
614 break;
615 }
616}
617
Chris Lattner6d492922002-08-19 21:32:41 +0000618// printConstant - The LLVM Constant to C Constant converter.
619void CWriter::printConstant(Constant *CPV) {
620 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
621 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000622 case Instruction::Trunc:
623 case Instruction::ZExt:
624 case Instruction::SExt:
625 case Instruction::FPTrunc:
626 case Instruction::FPExt:
627 case Instruction::UIToFP:
628 case Instruction::SIToFP:
629 case Instruction::FPToUI:
630 case Instruction::FPToSI:
631 case Instruction::PtrToInt:
632 case Instruction::IntToPtr:
633 case Instruction::BitCast:
634 Out << "(";
635 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
636 if (CE->getOpcode() == Instruction::SExt &&
637 CE->getOperand(0)->getType() == Type::BoolTy) {
638 // Make sure we really sext from bool here by subtracting from 0
639 Out << "0-";
640 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000641 printConstant(CE->getOperand(0));
Reid Spencer639cf7d2006-11-27 18:51:06 +0000642 if (CE->getType() == Type::BoolTy &&
643 (CE->getOpcode() == Instruction::Trunc ||
644 CE->getOpcode() == Instruction::FPToUI ||
645 CE->getOpcode() == Instruction::FPToSI ||
646 CE->getOpcode() == Instruction::PtrToInt)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000647 // Make sure we really truncate to bool here by anding with 1
648 Out << "&1u";
649 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000650 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000651 return;
652
653 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000654 Out << "(&(";
Chris Lattner23e90702003-11-25 20:49:55 +0000655 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
656 gep_type_end(CPV));
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000657 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000658 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000659 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000660 Out << '(';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000661 printConstant(CE->getOperand(0));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000662 Out << '?';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000663 printConstant(CE->getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000664 Out << ':';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000665 printConstant(CE->getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000666 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +0000667 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000668 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000669 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000670 case Instruction::Mul:
Reid Spencer1628cec2006-10-26 06:15:43 +0000671 case Instruction::SDiv:
672 case Instruction::UDiv:
673 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000674 case Instruction::URem:
675 case Instruction::SRem:
676 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000677 case Instruction::And:
678 case Instruction::Or:
679 case Instruction::Xor:
Chris Lattner29255922003-08-14 19:19:53 +0000680 case Instruction::SetEQ:
681 case Instruction::SetNE:
682 case Instruction::SetLT:
683 case Instruction::SetLE:
684 case Instruction::SetGT:
685 case Instruction::SetGE:
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000686 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000687 case Instruction::LShr:
688 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +0000689 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000690 Out << '(';
Reid Spencer1628cec2006-10-26 06:15:43 +0000691 bool NeedsClosingParens = printConstExprCast(CE);
692 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +0000693 switch (CE->getOpcode()) {
694 case Instruction::Add: Out << " + "; break;
695 case Instruction::Sub: Out << " - "; break;
696 case Instruction::Mul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +0000697 case Instruction::URem:
698 case Instruction::SRem:
699 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000700 case Instruction::UDiv:
701 case Instruction::SDiv:
702 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +0000703 case Instruction::And: Out << " & "; break;
704 case Instruction::Or: Out << " | "; break;
705 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000706 case Instruction::SetEQ: Out << " == "; break;
707 case Instruction::SetNE: Out << " != "; break;
708 case Instruction::SetLT: Out << " < "; break;
709 case Instruction::SetLE: Out << " <= "; break;
710 case Instruction::SetGT: Out << " > "; break;
711 case Instruction::SetGE: Out << " >= "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +0000712 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000713 case Instruction::LShr:
714 case Instruction::AShr: Out << " >> "; break;
Chris Lattner29255922003-08-14 19:19:53 +0000715 default: assert(0 && "Illegal opcode here!");
716 }
Reid Spencer1628cec2006-10-26 06:15:43 +0000717 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
718 if (NeedsClosingParens)
719 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000720 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000721 return;
Reid Spencer72ddc212006-10-26 06:17:40 +0000722 }
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000723
Chris Lattner6d492922002-08-19 21:32:41 +0000724 default:
725 std::cerr << "CWriter Error: Unhandled constant expression: "
Chris Lattner76e2df22004-07-15 02:14:30 +0000726 << *CE << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000727 abort();
728 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000729 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
Chris Lattner665825e2004-10-17 17:48:59 +0000730 Out << "((";
731 printType(Out, CPV->getType());
732 Out << ")/*UNDEF*/0)";
Chris Lattnera9d12c02004-10-16 18:12:13 +0000733 return;
Chris Lattner6d492922002-08-19 21:32:41 +0000734 }
735
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000736 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +0000737 case Type::BoolTyID:
Chris Lattner33ce7772006-09-28 23:19:29 +0000738 Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
739 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000740 case Type::SByteTyID:
741 case Type::ShortTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000742 Out << cast<ConstantInt>(CPV)->getSExtValue();
Chris Lattner33ce7772006-09-28 23:19:29 +0000743 break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000744 case Type::IntTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000745 if ((int)cast<ConstantInt>(CPV)->getSExtValue() == (int)0x80000000)
Chris Lattner40e7c352004-11-30 21:33:58 +0000746 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
Chris Lattner45343ea2003-05-12 15:39:31 +0000747 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000748 Out << cast<ConstantInt>(CPV)->getSExtValue();
Chris Lattner45343ea2003-05-12 15:39:31 +0000749 break;
750
Chris Lattner6d492922002-08-19 21:32:41 +0000751 case Type::LongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000752 if (cast<ConstantInt>(CPV)->isMinValue())
Chris Lattner40e7c352004-11-30 21:33:58 +0000753 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
754 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000755 Out << cast<ConstantInt>(CPV)->getSExtValue() << "ll";
Chris Lattner33ce7772006-09-28 23:19:29 +0000756 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000757
758 case Type::UByteTyID:
759 case Type::UShortTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000760 Out << cast<ConstantInt>(CPV)->getZExtValue();
Chris Lattner33ce7772006-09-28 23:19:29 +0000761 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000762 case Type::UIntTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000763 Out << cast<ConstantInt>(CPV)->getZExtValue() << 'u';
Chris Lattner33ce7772006-09-28 23:19:29 +0000764 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000765 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000766 Out << cast<ConstantInt>(CPV)->getZExtValue() << "ull";
Chris Lattner33ce7772006-09-28 23:19:29 +0000767 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000768
769 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000770 case Type::DoubleTyID: {
771 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000772 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000773 if (I != FPConstantMap.end()) {
774 // Because of FP precision problems we must load from a stack allocated
775 // value that holds the value in hex.
776 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000777 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000778 } else {
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000779 if (IsNAN(FPC->getValue())) {
780 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +0000781
Brian Gaeke8a702e82004-08-25 19:00:42 +0000782 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
783 // it's 0x7ff4.
784 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +0000785 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +0000786
787 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +0000788 char Buffer[100];
789
Jim Laskeycb6682f2005-08-17 19:34:49 +0000790 uint64_t ll = DoubleToBits(FPC->getValue());
Reid Spencer2bc320d2006-05-31 22:26:11 +0000791 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +0000792
793 std::string Num(&Buffer[0], &Buffer[6]);
794 unsigned long Val = strtoul(Num.c_str(), 0, 16);
795
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000796 if (FPC->getType() == Type::FloatTy)
Brian Gaeke8a702e82004-08-25 19:00:42 +0000797 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
798 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000799 else
Brian Gaeke8a702e82004-08-25 19:00:42 +0000800 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
801 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000802 } else if (IsInf(FPC->getValue())) {
803 // The value is Inf
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000804 if (FPC->getValue() < 0) Out << '-';
Brian Gaeke8a702e82004-08-25 19:00:42 +0000805 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
806 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000807 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +0000808 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +0000809#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +0000810 // Print out the constant as a floating point number.
811 char Buffer[100];
812 sprintf(Buffer, "%a", FPC->getValue());
813 Num = Buffer;
814#else
815 Num = ftostr(FPC->getValue());
816#endif
Brian Gaeke043c0bb2004-07-21 03:15:26 +0000817 Out << Num;
818 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000819 }
820 break;
821 }
Chris Lattner6d492922002-08-19 21:32:41 +0000822
823 case Type::ArrayTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000824 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000825 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000826 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000827 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000828 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000829 Constant *CZ = Constant::getNullValue(AT->getElementType());
830 printConstant(CZ);
831 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
832 Out << ", ";
833 printConstant(CZ);
834 }
835 }
836 Out << " }";
837 } else {
838 printConstantArray(cast<ConstantArray>(CPV));
839 }
Chris Lattner6d492922002-08-19 21:32:41 +0000840 break;
841
Robert Bocchinob78e8382006-01-20 20:43:57 +0000842 case Type::PackedTyID:
843 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
844 const PackedType *AT = cast<PackedType>(CPV->getType());
845 Out << '{';
846 if (AT->getNumElements()) {
847 Out << ' ';
848 Constant *CZ = Constant::getNullValue(AT->getElementType());
849 printConstant(CZ);
850 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
851 Out << ", ";
852 printConstant(CZ);
853 }
854 }
855 Out << " }";
856 } else {
857 printConstantPacked(cast<ConstantPacked>(CPV));
858 }
859 break;
860
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000861 case Type::StructTyID:
Chris Lattnera9d12c02004-10-16 18:12:13 +0000862 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000863 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000864 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000865 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000866 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000867 printConstant(Constant::getNullValue(ST->getElementType(0)));
868 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
869 Out << ", ";
870 printConstant(Constant::getNullValue(ST->getElementType(i)));
871 }
Chris Lattner6d492922002-08-19 21:32:41 +0000872 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000873 Out << " }";
874 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000875 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000876 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000877 Out << ' ';
Chris Lattnercfb0fd22004-02-15 05:54:27 +0000878 printConstant(cast<Constant>(CPV->getOperand(0)));
879 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
880 Out << ", ";
881 printConstant(cast<Constant>(CPV->getOperand(i)));
882 }
883 }
884 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +0000885 }
Chris Lattner6d492922002-08-19 21:32:41 +0000886 break;
Chris Lattner6d492922002-08-19 21:32:41 +0000887
888 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000889 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000890 Out << "((";
891 printType(Out, CPV->getType());
892 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000893 break;
Reid Spencer518310c2004-07-18 00:44:37 +0000894 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
895 writeOperand(GV);
Chris Lattner6d492922002-08-19 21:32:41 +0000896 break;
897 }
898 // FALL THROUGH
899 default:
Chris Lattner76e2df22004-07-15 02:14:30 +0000900 std::cerr << "Unknown constant type: " << *CPV << "\n";
Chris Lattner6d492922002-08-19 21:32:41 +0000901 abort();
902 }
903}
904
Reid Spencer1628cec2006-10-26 06:15:43 +0000905// Some constant expressions need to be casted back to the original types
906// because their operands were casted to the expected type. This function takes
907// care of detecting that case and printing the cast for the ConstantExpr.
908bool CWriter::printConstExprCast(const ConstantExpr* CE) {
Reid Spencer3822ff52006-11-08 06:47:33 +0000909 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +0000910 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +0000911 switch (CE->getOpcode()) {
Reid Spencer3822ff52006-11-08 06:47:33 +0000912 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +0000913 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +0000914 case Instruction::UDiv:
915 NeedsExplicitCast = Ty->isSigned(); break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000916 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +0000917 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +0000918 case Instruction::SDiv:
919 NeedsExplicitCast = Ty->isUnsigned(); break;
920 case Instruction::ZExt:
921 case Instruction::SExt:
922 case Instruction::Trunc:
923 case Instruction::FPTrunc:
924 case Instruction::FPExt:
925 case Instruction::UIToFP:
926 case Instruction::SIToFP:
927 case Instruction::FPToUI:
928 case Instruction::FPToSI:
929 case Instruction::PtrToInt:
930 case Instruction::IntToPtr:
931 case Instruction::BitCast:
932 Ty = CE->getType();
933 NeedsExplicitCast = true;
934 break;
Reid Spencer1628cec2006-10-26 06:15:43 +0000935 default: break;
936 }
Reid Spencer3822ff52006-11-08 06:47:33 +0000937 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000938 Out << "((";
939 printType(Out, Ty);
940 Out << ")(";
941 }
Reid Spencer3822ff52006-11-08 06:47:33 +0000942 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +0000943}
944
945// Print a constant assuming that it is the operand for a given Opcode. The
946// opcodes that care about sign need to cast their operands to the expected
947// type before the operation proceeds. This function does the casting.
948void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
949
950 // Extract the operand's type, we'll need it.
951 const Type* OpTy = CPV->getType();
952
953 // Indicate whether to do the cast or not.
954 bool shouldCast = false;
955
956 // Based on the Opcode for which this Constant is being written, determine
957 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +0000958 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
959 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +0000960 switch (Opcode) {
961 default:
962 // for most instructions, it doesn't matter
963 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000964 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000965 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000966 case Instruction::URem:
967 // For UDiv/URem get correct type
Reid Spencer1628cec2006-10-26 06:15:43 +0000968 if (OpTy->isSigned()) {
969 OpTy = OpTy->getUnsignedVersion();
970 shouldCast = true;
971 }
972 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000973 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +0000974 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000975 case Instruction::SRem:
976 // For SDiv/SRem get correct type
Reid Spencer1628cec2006-10-26 06:15:43 +0000977 if (OpTy->isUnsigned()) {
978 OpTy = OpTy->getSignedVersion();
979 shouldCast = true;
980 }
981 break;
982 }
983
Reid Spencer3da59db2006-11-27 01:05:10 +0000984 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +0000985 // operand.
986 if (shouldCast) {
987 Out << "((";
988 printType(Out, OpTy);
989 Out << ")";
990 printConstant(CPV);
991 Out << ")";
992 } else
993 writeOperand(CPV);
994
995}
996
Chris Lattner6d492922002-08-19 21:32:41 +0000997void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000998 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000999 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001000 // Should we inline this instruction to build a tree?
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001001 Out << '(';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001002 visit(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001003 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001004 return;
1005 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001006
Reid Spencer518310c2004-07-18 00:44:37 +00001007 Constant* CPV = dyn_cast<Constant>(Operand);
1008 if (CPV && !isa<GlobalValue>(CPV)) {
Misha Brukmand6a29a52005-04-20 16:05:03 +00001009 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001010 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001011 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001012 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001013}
1014
Andrew Lenharth29c277f2006-11-27 23:50:49 +00001015void CWriter::writeOperandRaw(Value *Operand) {
1016 Constant* CPV = dyn_cast<Constant>(Operand);
1017 if (CPV && !isa<GlobalValue>(CPV)) {
1018 printConstant(CPV);
1019 } else {
1020 Out << Mang->getValueName(Operand);
1021 }
1022}
1023
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001024void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001025 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Reid Spencer3da59db2006-11-27 01:05:10 +00001026 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001027
1028 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001029
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001030 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001031 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001032}
1033
Reid Spencer1628cec2006-10-26 06:15:43 +00001034// Some instructions need to have their result value casted back to the
1035// original types because their operands were casted to the expected type.
1036// This function takes care of detecting that case and printing the cast
1037// for the Instruction.
1038bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001039 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001040 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001041 switch (I.getOpcode()) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001042 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001043 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001044 case Instruction::UDiv:
1045 NeedsExplicitCast = Ty->isSigned(); break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001046 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001047 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001048 case Instruction::SDiv:
1049 NeedsExplicitCast = Ty->isUnsigned(); break;
1050 case Instruction::ZExt:
1051 case Instruction::SExt:
1052 case Instruction::Trunc:
1053 case Instruction::FPTrunc:
1054 case Instruction::FPExt:
1055 case Instruction::UIToFP:
1056 case Instruction::SIToFP:
1057 case Instruction::FPToUI:
1058 case Instruction::FPToSI:
1059 case Instruction::PtrToInt:
1060 case Instruction::IntToPtr:
1061 case Instruction::BitCast:
1062 Ty = I.getType();
1063 NeedsExplicitCast = true;
1064 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001065 default: break;
1066 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001067 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001068 Out << "((";
1069 printType(Out, Ty);
1070 Out << ")(";
1071 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001072 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001073}
1074
1075// Write the operand with a cast to another type based on the Opcode being used.
1076// This will be used in cases where an instruction has specific type
1077// requirements (usually signedness) for its operands.
1078void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1079
1080 // Extract the operand's type, we'll need it.
1081 const Type* OpTy = Operand->getType();
1082
1083 // Indicate whether to do the cast or not.
1084 bool shouldCast = false;
1085
1086 // Based on the Opcode for which this Operand is being written, determine
1087 // the new type to which the operand should be casted by setting the value
1088 // of OpTy. If we change OpTy, also set shouldCast to true.
1089 switch (Opcode) {
1090 default:
1091 // for most instructions, it doesn't matter
1092 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001093 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001094 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001095 case Instruction::URem:
Reid Spencer1628cec2006-10-26 06:15:43 +00001096 // For UDiv to have unsigned operands
1097 if (OpTy->isSigned()) {
1098 OpTy = OpTy->getUnsignedVersion();
1099 shouldCast = true;
1100 }
1101 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001102 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001103 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001104 case Instruction::SRem:
Reid Spencer1628cec2006-10-26 06:15:43 +00001105 if (OpTy->isUnsigned()) {
1106 OpTy = OpTy->getSignedVersion();
1107 shouldCast = true;
1108 }
1109 break;
1110 }
1111
1112 // Write out the casted operand if we should, otherwise just write the
1113 // operand.
1114 if (shouldCast) {
1115 Out << "((";
1116 printType(Out, OpTy);
1117 Out << ")";
1118 writeOperand(Operand);
1119 Out << ")";
1120 } else
1121 writeOperand(Operand);
1122
1123}
1124
Chris Lattner41488192003-06-28 17:15:12 +00001125// generateCompilerSpecificCode - This is where we add conditional compilation
1126// directives to cater to specific compilers as need be.
1127//
Chris Lattnerc59c1182003-11-16 22:06:14 +00001128static void generateCompilerSpecificCode(std::ostream& Out) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001129 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001130 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001131 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001132 << "extern void *_alloca(unsigned long);\n"
1133 << "#define alloca(x) _alloca(x)\n"
1134 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001135 << "extern void *__builtin_alloca(unsigned long);\n"
1136 << "#define alloca(x) __builtin_alloca(x)\n"
Brian Gaekece630052004-12-10 05:44:45 +00001137 << "#elif defined(__sun__)\n"
1138 << "#if defined(__sparcv9)\n"
1139 << "extern void *__builtin_alloca(unsigned long);\n"
1140 << "#else\n"
1141 << "extern void *__builtin_alloca(unsigned int);\n"
1142 << "#endif\n"
1143 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohen3c280bf2006-04-17 17:55:41 +00001144 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001145 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohend01f65a2005-01-06 04:21:49 +00001146 << "#elif !defined(_MSC_VER)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001147 << "#include <alloca.h>\n"
1148 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001149
1150 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1151 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001152 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001153 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001154 << "#endif\n\n";
1155
1156#if 0
1157 // At some point, we should support "external weak" vs. "weak" linkages.
1158 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1159 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1160 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1161 << "#elif defined(__GNUC__)\n"
1162 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1163 << "#else\n"
1164 << "#define __EXTERNAL_WEAK__\n"
1165 << "#endif\n\n";
1166#endif
1167
1168 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1169 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1170 << "#define __ATTRIBUTE_WEAK__\n"
1171 << "#elif defined(__GNUC__)\n"
1172 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1173 << "#else\n"
1174 << "#define __ATTRIBUTE_WEAK__\n"
1175 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001176
1177 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1178 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001179 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001180 // double __builtin_nan (const char *str)
1181 //
1182 // This is an implementation of the ISO C99 function nan.
1183 //
1184 // Since ISO C99 defines this function in terms of strtod, which we do
1185 // not implement, a description of the parsing is in order. The string is
1186 // parsed as by strtol; that is, the base is recognized by leading 0 or
1187 // 0x prefixes. The number parsed is placed in the significand such that
1188 // the least significant bit of the number is at the least significant
1189 // bit of the significand. The number is truncated to fit the significand
1190 // field provided. The significand is forced to be a quiet NaN.
1191 //
1192 // This function, if given a string literal, is evaluated early enough
1193 // that it is considered a compile-time constant.
1194 //
1195 // float __builtin_nanf (const char *str)
1196 //
1197 // Similar to __builtin_nan, except the return type is float.
1198 //
1199 // double __builtin_inf (void)
1200 //
1201 // Similar to __builtin_huge_val, except a warning is generated if the
1202 // target floating-point format does not support infinities. This
1203 // function is suitable for implementing the ISO C99 macro INFINITY.
1204 //
1205 // float __builtin_inff (void)
1206 //
1207 // Similar to __builtin_inf, except the return type is float.
1208 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001209 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1210 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1211 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1212 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1213 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1214 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001215 << "#define LLVM_PREFETCH(addr,rw,locality) "
1216 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001217 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1218 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001219 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001220 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001221 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1222 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1223 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1224 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1225 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1226 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001227 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001228 << "#define __ATTRIBUTE_CTOR__\n"
1229 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001230 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001231 << "#endif\n\n";
1232
1233 // Output target-specific code that should be inserted into main.
1234 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1235 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1236 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
Evan Chenge3db4da2006-06-20 22:11:12 +00001237 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1238 << "defined(__x86_64__)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001239 << "#undef CODE_FOR_MAIN\n"
1240 << "#define CODE_FOR_MAIN() \\\n"
1241 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1242 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1243 << "#endif\n#endif\n";
1244
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001245}
1246
Chris Lattner9a571ba2006-03-07 22:58:23 +00001247/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1248/// the StaticTors set.
1249static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1250 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1251 if (!InitList) return;
1252
1253 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1255 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1256
1257 if (CS->getOperand(1)->isNullValue())
1258 return; // Found a null terminator, exit printing.
1259 Constant *FP = CS->getOperand(1);
1260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001261 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001262 FP = CE->getOperand(0);
1263 if (Function *F = dyn_cast<Function>(FP))
1264 StaticTors.insert(F);
1265 }
1266}
1267
1268enum SpecialGlobalClass {
1269 NotSpecial = 0,
1270 GlobalCtors, GlobalDtors,
1271 NotPrinted
1272};
1273
1274/// getGlobalVariableClass - If this is a global that is specially recognized
1275/// by LLVM, return a code that indicates how we should handle it.
1276static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1277 // If this is a global ctors/dtors list, handle it now.
1278 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1279 if (GV->getName() == "llvm.global_ctors")
1280 return GlobalCtors;
1281 else if (GV->getName() == "llvm.global_dtors")
1282 return GlobalDtors;
1283 }
1284
1285 // Otherwise, it it is other metadata, don't print it. This catches things
1286 // like debug information.
1287 if (GV->getSection() == "llvm.metadata")
1288 return NotPrinted;
1289
1290 return NotSpecial;
1291}
1292
1293
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001294bool CWriter::doInitialization(Module &M) {
1295 // Initialize
1296 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001297
1298 IL.AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001299
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001300 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001301 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001302 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001303
Chris Lattner9a571ba2006-03-07 22:58:23 +00001304 // Keep track of which functions are static ctors/dtors so they can have
1305 // an attribute added to their prototypes.
1306 std::set<Function*> StaticCtors, StaticDtors;
1307 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1308 I != E; ++I) {
1309 switch (getGlobalVariableClass(I)) {
1310 default: break;
1311 case GlobalCtors:
1312 FindStaticTors(I, StaticCtors);
1313 break;
1314 case GlobalDtors:
1315 FindStaticTors(I, StaticDtors);
1316 break;
1317 }
1318 }
1319
Chris Lattner16c7bb22002-05-09 02:28:59 +00001320 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001321 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001322 Out << "#include <stdarg.h>\n"; // Varargs support
1323 Out << "#include <setjmp.h>\n"; // Unwind support
Chris Lattner41488192003-06-28 17:15:12 +00001324 generateCompilerSpecificCode(Out);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001325
Chris Lattnercf135cb2003-06-02 03:10:53 +00001326 // Provide a definition for `bool' if not compiling with a C++ compiler.
1327 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001328 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001329
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001330 << "\n\n/* Support for floating point constants */\n"
1331 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001332 << "typedef unsigned int ConstantFloatTy;\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001333
Chris Lattnera4d4a852002-08-19 21:48:40 +00001334 << "\n\n/* Global Declarations */\n";
1335
1336 // First output all the declarations for the program, because C requires
1337 // Functions & globals to be declared before they are used.
1338 //
Chris Lattner16c7bb22002-05-09 02:28:59 +00001339
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001340 // Loop over the symbol table, emitting all named constants...
Chris Lattner68758072004-05-09 06:20:51 +00001341 printModuleTypes(M.getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001342
Chris Lattnera4d4a852002-08-19 21:48:40 +00001343 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001344 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001345 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001346 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1347 I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001348 if (I->hasExternalLinkage()) {
1349 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001350 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001351 Out << ";\n";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001352 } else if (I->hasDLLImportLinkage()) {
1353 Out << "__declspec(dllimport) ";
1354 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1355 Out << ";\n";
1356 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001357 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001358 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001359
Chris Lattnera4d4a852002-08-19 21:48:40 +00001360 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001361 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001362 Out << "double fmod(double, double);\n"; // Support for FP rem
1363 Out << "float fmodf(float, float);\n";
1364
Chris Lattner9a571ba2006-03-07 22:58:23 +00001365 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1366 // Don't print declarations for intrinsic functions.
Reid Spencer2cb46e12006-10-22 09:58:21 +00001367 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1368 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001369 printFunctionSignature(I, true);
1370 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1371 Out << " __ATTRIBUTE_WEAK__";
1372 if (StaticCtors.count(I))
1373 Out << " __ATTRIBUTE_CTOR__";
1374 if (StaticDtors.count(I))
1375 Out << " __ATTRIBUTE_DTOR__";
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001376
1377 if (I->hasName() && I->getName()[0] == 1)
1378 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1379
Chris Lattner9a571ba2006-03-07 22:58:23 +00001380 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001381 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001382 }
1383
Joel Stanley54f60322003-06-25 04:52:09 +00001384 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001385 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001386 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001387 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1388 I != E; ++I)
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001389 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001390 // Ignore special globals, such as debug info.
1391 if (getGlobalVariableClass(I))
1392 continue;
1393
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001394 if (I->hasInternalLinkage())
1395 Out << "static ";
1396 else
1397 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001398 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00001399
1400 if (I->hasLinkOnceLinkage())
1401 Out << " __attribute__((common))";
1402 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001403 Out << " __ATTRIBUTE_WEAK__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00001404 Out << ";\n";
1405 }
1406 }
1407
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001408 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001409 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001410 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001411 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1412 I != E; ++I)
Chris Lattnere8e035b2002-10-16 20:08:47 +00001413 if (!I->isExternal()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001414 // Ignore special globals, such as debug info.
1415 if (getGlobalVariableClass(I))
1416 continue;
1417
Chris Lattnere8e035b2002-10-16 20:08:47 +00001418 if (I->hasInternalLinkage())
1419 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001420 else if (I->hasDLLImportLinkage())
1421 Out << "__declspec(dllimport) ";
1422 else if (I->hasDLLExportLinkage())
1423 Out << "__declspec(dllexport) ";
1424
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001425 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00001426 if (I->hasLinkOnceLinkage())
1427 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00001428 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00001429 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00001430
1431 // If the initializer is not null, emit the initializer. If it is null,
1432 // we try to avoid emitting large amounts of zeros. The problem with
1433 // this, however, occurs when the variable has weak linkage. In this
1434 // case, the assembler will complain about the variable being both weak
1435 // and common, so we disable this optimization.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001436 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00001437 Out << " = " ;
1438 writeOperand(I->getInitializer());
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001439 } else if (I->hasWeakLinkage()) {
1440 // We have to specify an initializer, but it doesn't have to be
1441 // complete. If the value is an aggregate, print out { 0 }, and let
1442 // the compiler figure out the rest of the zeros.
1443 Out << " = " ;
1444 if (isa<StructType>(I->getInitializer()->getType()) ||
Robert Bocchinob78e8382006-01-20 20:43:57 +00001445 isa<ArrayType>(I->getInitializer()->getType()) ||
1446 isa<PackedType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00001447 Out << "{ 0 }";
1448 } else {
1449 // Just print it out normally.
1450 writeOperand(I->getInitializer());
1451 }
Chris Lattner940b08d2003-06-06 07:10:24 +00001452 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00001453 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00001454 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001455 }
1456
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001457 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00001458 Out << "\n\n/* Function Bodies */\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001459 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001460}
1461
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001462
Chris Lattner9860e772003-10-12 04:36:29 +00001463/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00001464void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00001465 // Scan the module for floating point constants. If any FP constant is used
1466 // in the function, we want to redirect it here so that we do not depend on
1467 // the precision of the printed form, unless the printed form preserves
1468 // precision.
1469 //
Chris Lattner68758072004-05-09 06:20:51 +00001470 static unsigned FPCounter = 0;
1471 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1472 I != E; ++I)
1473 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1474 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1475 !FPConstantMap.count(FPC)) {
1476 double Val = FPC->getValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00001477
Chris Lattner68758072004-05-09 06:20:51 +00001478 FPConstantMap[FPC] = FPCounter; // Number the FP constants
Misha Brukmand6a29a52005-04-20 16:05:03 +00001479
Chris Lattner68758072004-05-09 06:20:51 +00001480 if (FPC->getType() == Type::DoubleTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001481 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001482 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001483 << "ULL; /* " << Val << " */\n";
1484 } else if (FPC->getType() == Type::FloatTy) {
Chris Lattner68758072004-05-09 06:20:51 +00001485 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
Jim Laskeycb6682f2005-08-17 19:34:49 +00001486 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
Chris Lattner68758072004-05-09 06:20:51 +00001487 << "U; /* " << Val << " */\n";
1488 } else
1489 assert(0 && "Unknown float type!");
1490 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001491
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001492 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00001493}
Chris Lattner9860e772003-10-12 04:36:29 +00001494
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001495
Chris Lattner2db41cd2002-09-20 15:12:13 +00001496/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00001497/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00001498///
Chris Lattner68758072004-05-09 06:20:51 +00001499void CWriter::printModuleTypes(const SymbolTable &ST) {
Chris Lattnerb15fde22005-03-06 02:28:23 +00001500 // We are only interested in the type plane of the symbol table.
Reid Spencer9231ac82004-05-25 08:53:40 +00001501 SymbolTable::type_const_iterator I = ST.type_begin();
1502 SymbolTable::type_const_iterator End = ST.type_end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00001503
1504 // If there are no type names, exit early.
1505 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00001506
Chris Lattner58d04d42002-09-20 15:18:30 +00001507 // Print out forward declarations for structure types before anything else!
1508 Out << "/* Structure forward decls */\n";
1509 for (; I != End; ++I)
Chris Lattner68758072004-05-09 06:20:51 +00001510 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Chris Lattner36c975c2005-11-10 18:53:25 +00001511 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001512 Out << Name << ";\n";
1513 TypeNames.insert(std::make_pair(STy, Name));
1514 }
Chris Lattner58d04d42002-09-20 15:18:30 +00001515
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001516 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00001517
1518 // Now we can print out typedefs...
1519 Out << "/* Typedefs */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001520 for (I = ST.type_begin(); I != End; ++I) {
Chris Lattner68758072004-05-09 06:20:51 +00001521 const Type *Ty = cast<Type>(I->second);
Chris Lattner36c975c2005-11-10 18:53:25 +00001522 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00001523 Out << "typedef ";
1524 printType(Out, Ty, Name);
1525 Out << ";\n";
1526 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001527
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001528 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00001529
Chris Lattner2c601a72002-09-20 15:05:40 +00001530 // Keep track of which structures have been printed so far...
1531 std::set<const StructType *> StructPrinted;
1532
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001533 // Loop over all structures then push them into the stack so they are
1534 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00001535 //
Chris Lattner58d04d42002-09-20 15:18:30 +00001536 Out << "/* Structure contents */\n";
Reid Spencer9231ac82004-05-25 08:53:40 +00001537 for (I = ST.type_begin(); I != End; ++I)
Chris Lattner2db41cd2002-09-20 15:12:13 +00001538 if (const StructType *STy = dyn_cast<StructType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00001539 // Only print out used types!
Chris Lattner68758072004-05-09 06:20:51 +00001540 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001541}
1542
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001543// Push the struct onto the stack and recursively push all structs
1544// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00001545//
1546// TODO: Make this work properly with packed types
1547//
Chris Lattner2c601a72002-09-20 15:05:40 +00001548void CWriter::printContainedStructs(const Type *Ty,
1549 std::set<const StructType*> &StructPrinted){
Chris Lattner14d9b202006-01-20 18:57:03 +00001550 // Don't walk through pointers.
1551 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1552
1553 // Print all contained types first.
1554 for (Type::subtype_iterator I = Ty->subtype_begin(),
1555 E = Ty->subtype_end(); I != E; ++I)
1556 printContainedStructs(*I, StructPrinted);
1557
Misha Brukmanac25de32003-07-09 17:33:50 +00001558 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00001559 // Check to see if we have already printed this struct.
1560 if (StructPrinted.insert(STy).second) {
1561 // Print structure type out.
Misha Brukmand6a29a52005-04-20 16:05:03 +00001562 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001563 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00001564 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001565 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00001566 }
1567}
1568
Chris Lattner4cda8352002-08-20 16:55:48 +00001569void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001570 /// isCStructReturn - Should this function actually return a struct by-value?
1571 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1572
Joel Stanley54f60322003-06-25 04:52:09 +00001573 if (F->hasInternalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001574 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1575 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00001576 switch (F->getCallingConv()) {
1577 case CallingConv::X86_StdCall:
1578 Out << "__stdcall ";
1579 break;
1580 case CallingConv::X86_FastCall:
1581 Out << "__fastcall ";
1582 break;
1583 }
1584
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001585 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001586 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Misha Brukmand6a29a52005-04-20 16:05:03 +00001587
1588 std::stringstream FunctionInnards;
1589
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001590 // Print out the name...
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001591 FunctionInnards << Mang->getValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00001592
Chris Lattner0c54d892006-05-23 23:39:48 +00001593 bool PrintedArg = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001594 if (!F->isExternal()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00001595 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001596 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1597
1598 // If this is a struct-return function, don't print the hidden
1599 // struct-return argument.
1600 if (isCStructReturn) {
1601 assert(I != E && "Invalid struct return function!");
1602 ++I;
1603 }
1604
Chris Lattneredd8ce12003-05-03 03:14:35 +00001605 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00001606 for (; I != E; ++I) {
1607 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00001608 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001609 ArgName = Mang->getValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001610 else
Chris Lattner4cda8352002-08-20 16:55:48 +00001611 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +00001612 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00001613 PrintedArg = true;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001614 }
1615 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001616 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00001617 // Loop over the arguments, printing them.
1618 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1619
1620 // If this is a struct-return function, don't print the hidden
1621 // struct-return argument.
1622 if (isCStructReturn) {
1623 assert(I != E && "Invalid struct return function!");
1624 ++I;
1625 }
1626
1627 for (; I != E; ++I) {
1628 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001629 printType(FunctionInnards, *I);
Chris Lattner0c54d892006-05-23 23:39:48 +00001630 PrintedArg = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001631 }
1632 }
1633
Chris Lattner1f8c4a12002-09-20 22:32:30 +00001634 // Finish printing arguments... if this is a vararg function, print the ...,
1635 // unless there are no known types, in which case, we just emit ().
1636 //
Chris Lattner0c54d892006-05-23 23:39:48 +00001637 if (FT->isVarArg() && PrintedArg) {
1638 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00001639 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00001640 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00001641 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001642 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001643 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00001644
1645 // Get the return tpe for the function.
1646 const Type *RetTy;
1647 if (!isCStructReturn)
1648 RetTy = F->getReturnType();
1649 else {
1650 // If this is a struct-return function, print the struct-return type.
1651 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1652 }
1653
1654 // Print out the return type and the signature built above.
1655 printType(Out, RetTy, FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001656}
1657
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001658void CWriter::printFunction(Function &F) {
1659 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001660 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001661
1662 // If this is a struct return function, handle the result with magic.
1663 if (F.getCallingConv() == CallingConv::CSRet) {
1664 const Type *StructTy =
1665 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1666 Out << " ";
1667 printType(Out, StructTy, "StructReturn");
1668 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001669
Chris Lattner0c54d892006-05-23 23:39:48 +00001670 Out << " ";
1671 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1672 Out << " = &StructReturn;\n";
1673 }
1674
1675 bool PrintedVar = false;
1676
Chris Lattner497e19a2002-05-09 20:39:03 +00001677 // print local variable information for the function
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001678 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00001679 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001680 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001681 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00001682 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00001683 PrintedVar = true;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001684 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00001685 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001686 printType(Out, I->getType(), Mang->getValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001687 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001688
Chris Lattner84e66652003-05-03 07:11:00 +00001689 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1690 Out << " ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00001691 printType(Out, I->getType(),
1692 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00001693 Out << ";\n";
1694 }
Chris Lattner0c54d892006-05-23 23:39:48 +00001695 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001696 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001697
Chris Lattner0c54d892006-05-23 23:39:48 +00001698 if (PrintedVar)
1699 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001700
Chris Lattner395fd592004-12-13 21:52:52 +00001701 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00001702 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00001703
Chris Lattner16c7bb22002-05-09 02:28:59 +00001704 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001705 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001706 if (Loop *L = LI->getLoopFor(BB)) {
1707 if (L->getHeader() == BB && L->getParentLoop() == 0)
1708 printLoop(L);
1709 } else {
1710 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001711 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001712 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001713
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00001714 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001715}
1716
Chris Lattnercb3ad012004-05-09 20:41:32 +00001717void CWriter::printLoop(Loop *L) {
1718 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1719 << "' to make GCC happy */\n";
1720 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1721 BasicBlock *BB = L->getBlocks()[i];
1722 Loop *BBLoop = LI->getLoopFor(BB);
1723 if (BBLoop == L)
1724 printBasicBlock(BB);
1725 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00001726 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00001727 }
1728 Out << " } while (1); /* end of syntactic loop '"
1729 << L->getHeader()->getName() << "' */\n";
1730}
1731
1732void CWriter::printBasicBlock(BasicBlock *BB) {
1733
1734 // Don't print the label for the basic block if there are no uses, or if
1735 // the only terminator use is the predecessor basic block's terminator.
1736 // We have to scan the use list because PHI nodes use basic blocks too but
1737 // do not require a label to be generated.
1738 //
1739 bool NeedsLabel = false;
1740 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1741 if (isGotoCodeNecessary(*PI, BB)) {
1742 NeedsLabel = true;
1743 break;
1744 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001745
Chris Lattnercb3ad012004-05-09 20:41:32 +00001746 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001747
Chris Lattnercb3ad012004-05-09 20:41:32 +00001748 // Output all of the instructions in the basic block...
1749 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1750 ++II) {
1751 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00001752 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00001753 outputLValue(II);
1754 else
1755 Out << " ";
1756 visit(*II);
1757 Out << ";\n";
1758 }
1759 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001760
Chris Lattnercb3ad012004-05-09 20:41:32 +00001761 // Don't emit prefix or suffix for the terminator...
1762 visit(*BB->getTerminator());
1763}
1764
1765
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001766// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00001767// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001768//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001769void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00001770 // If this is a struct return function, return the temporary struct.
1771 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1772 Out << " return StructReturn;\n";
1773 return;
1774 }
1775
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001776 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00001777 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001778 &*--I.getParent()->getParent()->end() == I.getParent() &&
1779 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001780 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00001781 }
Chris Lattner44408262002-05-09 03:50:42 +00001782
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001783 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001784 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001785 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001786 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00001787 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001788 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001789}
1790
Chris Lattnera9f5e052003-04-22 20:19:52 +00001791void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001792
Chris Lattnera9f5e052003-04-22 20:19:52 +00001793 Out << " switch (";
1794 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00001795 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00001796 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00001797 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001798 Out << ";\n";
1799 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1800 Out << " case ";
1801 writeOperand(SI.getOperand(i));
1802 Out << ":\n";
1803 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00001804 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00001805 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00001806 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00001807 Out << " break;\n";
1808 }
1809 Out << " }\n";
1810}
1811
Chris Lattnera9d12c02004-10-16 18:12:13 +00001812void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00001813 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00001814}
1815
Chris Lattnercb3ad012004-05-09 20:41:32 +00001816bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1817 /// FIXME: This should be reenabled, but loop reordering safe!!
1818 return true;
1819
Chris Lattner67c2d182005-03-18 16:12:37 +00001820 if (next(Function::iterator(From)) != Function::iterator(To))
1821 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00001822
1823 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00001824
Chris Lattnercb3ad012004-05-09 20:41:32 +00001825 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001826 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001827 return false;
1828}
1829
John Criswell57bbfce2004-10-20 14:38:39 +00001830void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00001831 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00001832 unsigned Indent) {
1833 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1834 PHINode *PN = cast<PHINode>(I);
1835 // Now we have to do the printing.
1836 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1837 if (!isa<UndefValue>(IV)) {
1838 Out << std::string(Indent, ' ');
1839 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1840 writeOperand(IV);
1841 Out << "; /* for PHI node */\n";
1842 }
1843 }
1844}
1845
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001846void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001847 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00001848 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001849 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001850 writeOperand(Succ);
1851 Out << ";\n";
1852 }
1853}
1854
Misha Brukman37f92e22003-09-11 22:34:13 +00001855// Branch instruction printing - Avoid printing out a branch to a basic block
1856// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001857//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001858void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00001859
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001860 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001861 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001862 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001863 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001864 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00001865
John Criswell57bbfce2004-10-20 14:38:39 +00001866 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001867 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001868
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001869 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001870 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00001871 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001872 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001873 }
1874 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001875 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001876 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001877 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001878 Out << ") {\n";
1879
John Criswell57bbfce2004-10-20 14:38:39 +00001880 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001881 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001882 }
1883
1884 Out << " }\n";
1885 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00001886 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001887 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001888 }
1889 Out << "\n";
1890}
1891
Chris Lattner84e66652003-05-03 07:11:00 +00001892// PHI nodes get copied into temporary values at the end of predecessor basic
1893// blocks. We now need to copy these temporary values into the REAL value for
1894// the PHI.
1895void CWriter::visitPHINode(PHINode &I) {
1896 writeOperand(&I);
1897 Out << "__PHI_TEMPORARY";
1898}
1899
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001900
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001901void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001902 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001903 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001904
1905 // We must cast the results of binary operations which might be promoted.
1906 bool needsCast = false;
1907 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001908 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1909 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001910 needsCast = true;
1911 Out << "((";
Chris Lattner7635ea42003-11-03 01:01:59 +00001912 printType(Out, I.getType());
Brian Gaeke031a1122003-06-23 20:00:51 +00001913 Out << ")(";
1914 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001915
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001916 // If this is a negation operation, print it out as such. For FP, we don't
1917 // want to print "-0.0 - X".
1918 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00001919 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001920 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00001921 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00001922 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00001923 // Output a call to fmod/fmodf instead of emitting a%b
1924 if (I.getType() == Type::FloatTy)
1925 Out << "fmodf(";
1926 else
1927 Out << "fmod(";
1928 writeOperand(I.getOperand(0));
1929 Out << ", ";
1930 writeOperand(I.getOperand(1));
1931 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001932 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00001933
1934 // Write out the cast of the instruction's value back to the proper type
1935 // if necessary.
1936 bool NeedsClosingParens = writeInstructionCast(I);
1937
1938 // Certain instructions require the operand to be forced to a specific type
1939 // so we use writeOperandWithCast here instead of writeOperand. Similarly
1940 // below for operand 1
1941 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001942
1943 switch (I.getOpcode()) {
1944 case Instruction::Add: Out << " + "; break;
1945 case Instruction::Sub: Out << " - "; break;
1946 case Instruction::Mul: Out << '*'; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001947 case Instruction::URem:
1948 case Instruction::SRem:
1949 case Instruction::FRem: Out << '%'; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001950 case Instruction::UDiv:
1951 case Instruction::SDiv:
1952 case Instruction::FDiv: Out << '/'; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001953 case Instruction::And: Out << " & "; break;
1954 case Instruction::Or: Out << " | "; break;
1955 case Instruction::Xor: Out << " ^ "; break;
1956 case Instruction::SetEQ: Out << " == "; break;
1957 case Instruction::SetNE: Out << " != "; break;
1958 case Instruction::SetLE: Out << " <= "; break;
1959 case Instruction::SetGE: Out << " >= "; break;
1960 case Instruction::SetLT: Out << " < "; break;
1961 case Instruction::SetGT: Out << " > "; break;
1962 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001963 case Instruction::LShr:
1964 case Instruction::AShr: Out << " >> "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00001965 default: std::cerr << "Invalid operator type!" << I; abort();
1966 }
1967
Reid Spencer1628cec2006-10-26 06:15:43 +00001968 writeOperandWithCast(I.getOperand(1), I.getOpcode());
1969 if (NeedsClosingParens)
1970 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001971 }
1972
Brian Gaeke031a1122003-06-23 20:00:51 +00001973 if (needsCast) {
1974 Out << "))";
1975 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001976}
1977
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001978void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001979 const Type *DstTy = I.getType();
1980 const Type *SrcTy = I.getOperand(0)->getType();
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001981 Out << '(';
Reid Spencer3da59db2006-11-27 01:05:10 +00001982 printCast(I.getOpcode(), SrcTy, DstTy);
1983 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
1984 // Make sure we really get a sext from bool by subtracing the bool from 0
1985 Out << "0-";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001986 }
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001987 writeOperand(I.getOperand(0));
Reid Spencer639cf7d2006-11-27 18:51:06 +00001988 if (DstTy == Type::BoolTy &&
1989 (I.getOpcode() == Instruction::Trunc ||
1990 I.getOpcode() == Instruction::FPToUI ||
1991 I.getOpcode() == Instruction::FPToSI ||
1992 I.getOpcode() == Instruction::PtrToInt)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001993 // Make sure we really get a trunc to bool by anding the operand with 1
1994 Out << "&1u";
1995 }
1996 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001997}
1998
Chris Lattner9f24a072004-03-12 05:52:14 +00001999void CWriter::visitSelectInst(SelectInst &I) {
2000 Out << "((";
2001 writeOperand(I.getCondition());
2002 Out << ") ? (";
2003 writeOperand(I.getTrueValue());
2004 Out << ") : (";
2005 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002006 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002007}
2008
2009
Chris Lattnerc2421432004-05-09 04:30:20 +00002010void CWriter::lowerIntrinsics(Function &F) {
2011 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2012 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2013 if (CallInst *CI = dyn_cast<CallInst>(I++))
2014 if (Function *F = CI->getCalledFunction())
2015 switch (F->getIntrinsicID()) {
2016 case Intrinsic::not_intrinsic:
2017 case Intrinsic::vastart:
2018 case Intrinsic::vacopy:
2019 case Intrinsic::vaend:
2020 case Intrinsic::returnaddress:
2021 case Intrinsic::frameaddress:
2022 case Intrinsic::setjmp:
2023 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002024 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00002025 case Intrinsic::dbg_stoppoint:
Chris Lattner1e142892006-09-09 06:17:12 +00002026 case Intrinsic::powi_f32:
2027 case Intrinsic::powi_f64:
Chris Lattnerc2421432004-05-09 04:30:20 +00002028 // We directly implement these intrinsics
2029 break;
2030 default:
Chris Lattner87242152006-03-13 23:09:05 +00002031 // If this is an intrinsic that directly corresponds to a GCC
2032 // builtin, we handle it.
2033 const char *BuiltinName = "";
2034#define GET_GCC_BUILTIN_NAME
2035#include "llvm/Intrinsics.gen"
2036#undef GET_GCC_BUILTIN_NAME
2037 // If we handle it, don't lower it.
2038 if (BuiltinName[0]) break;
2039
Chris Lattnerc2421432004-05-09 04:30:20 +00002040 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002041 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002042 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002043 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002044
Chris Lattnerc2421432004-05-09 04:30:20 +00002045 IL.LowerIntrinsicCall(CI);
2046 if (Before) { // Move iterator to instruction after call
2047 I = Before; ++I;
2048 } else {
2049 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002050 }
Chris Lattner87242152006-03-13 23:09:05 +00002051 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002052 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002053}
2054
2055
2056
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002057void CWriter::visitCallInst(CallInst &I) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002058 //check if we have inline asm
2059 if (isInlineAsm(I)) {
2060 visitInlineAsm(I);
2061 return;
2062 }
2063
Chris Lattner87242152006-03-13 23:09:05 +00002064 bool WroteCallee = false;
2065
Chris Lattner18ac3c82003-05-08 18:41:45 +00002066 // Handle intrinsic function calls first...
2067 if (Function *F = I.getCalledFunction())
Brian Gaeked0fde302003-11-11 22:41:34 +00002068 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00002069 switch (ID) {
Chris Lattner87242152006-03-13 23:09:05 +00002070 default: {
2071 // If this is an intrinsic that directly corresponds to a GCC
2072 // builtin, we emit it here.
2073 const char *BuiltinName = "";
2074#define GET_GCC_BUILTIN_NAME
2075#include "llvm/Intrinsics.gen"
2076#undef GET_GCC_BUILTIN_NAME
2077 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2078
2079 Out << BuiltinName;
2080 WroteCallee = true;
2081 break;
2082 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002083 case Intrinsic::vastart:
Chris Lattner4d45bd02003-10-18 05:57:43 +00002084 Out << "0; ";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002085
Andrew Lenharth558bc882005-06-18 18:34:52 +00002086 Out << "va_start(*(va_list*)";
2087 writeOperand(I.getOperand(1));
2088 Out << ", ";
Chris Lattner18ac3c82003-05-08 18:41:45 +00002089 // Output the last argument to the enclosing function...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002090 if (I.getParent()->getParent()->arg_empty()) {
Chris Lattner4065ef92003-10-23 18:39:22 +00002091 std::cerr << "The C backend does not currently support zero "
2092 << "argument varargs functions, such as '"
2093 << I.getParent()->getParent()->getName() << "'!\n";
2094 abort();
2095 }
Chris Lattnerc5e7df12005-03-15 04:59:17 +00002096 writeOperand(--I.getParent()->getParent()->arg_end());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002097 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00002098 return;
Chris Lattner317201d2004-03-13 00:24:00 +00002099 case Intrinsic::vaend:
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002100 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002101 Out << "0; va_end(*(va_list*)";
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002102 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002103 Out << ')';
Chris Lattnerf8e6f4f2004-08-10 00:19:16 +00002104 } else {
2105 Out << "va_end(*(va_list*)0)";
2106 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00002107 return;
Chris Lattner317201d2004-03-13 00:24:00 +00002108 case Intrinsic::vacopy:
Andrew Lenharth558bc882005-06-18 18:34:52 +00002109 Out << "0; ";
2110 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00002111 writeOperand(I.getOperand(1));
Andrew Lenharth213e5572005-06-22 21:04:42 +00002112 Out << ", *(va_list*)";
Andrew Lenharth558bc882005-06-18 18:34:52 +00002113 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002114 Out << ')';
Chris Lattner18ac3c82003-05-08 18:41:45 +00002115 return;
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002116 case Intrinsic::returnaddress:
2117 Out << "__builtin_return_address(";
2118 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002119 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002120 return;
2121 case Intrinsic::frameaddress:
2122 Out << "__builtin_frame_address(";
2123 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002124 Out << ')';
Chris Lattnerfe1554a2004-02-14 02:55:36 +00002125 return;
Chris Lattner1e142892006-09-09 06:17:12 +00002126 case Intrinsic::powi_f32:
2127 case Intrinsic::powi_f64:
2128 Out << "__builtin_powi(";
2129 writeOperand(I.getOperand(1));
2130 Out << ", ";
2131 writeOperand(I.getOperand(2));
2132 Out << ')';
2133 return;
Chris Lattnere42cde22004-02-15 22:51:47 +00002134 case Intrinsic::setjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00002135#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2136 Out << "_"; // Use _setjmp on systems that support it!
2137#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00002138 Out << "setjmp(*(jmp_buf*)";
2139 writeOperand(I.getOperand(1));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002140 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00002141 return;
2142 case Intrinsic::longjmp:
Chris Lattner475c5532006-06-06 21:45:47 +00002143#if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2144 Out << "_"; // Use _longjmp on systems that support it!
2145#endif
Chris Lattnere42cde22004-02-15 22:51:47 +00002146 Out << "longjmp(*(jmp_buf*)";
2147 writeOperand(I.getOperand(1));
2148 Out << ", ";
2149 writeOperand(I.getOperand(2));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002150 Out << ')';
Chris Lattnere42cde22004-02-15 22:51:47 +00002151 return;
Chris Lattner33e9d292005-02-28 19:29:46 +00002152 case Intrinsic::prefetch:
Chris Lattnerca76f352005-02-28 19:36:15 +00002153 Out << "LLVM_PREFETCH((const void *)";
Chris Lattner33e9d292005-02-28 19:29:46 +00002154 writeOperand(I.getOperand(1));
2155 Out << ", ";
2156 writeOperand(I.getOperand(2));
2157 Out << ", ";
2158 writeOperand(I.getOperand(3));
2159 Out << ")";
Chris Lattnerca76f352005-02-28 19:36:15 +00002160 return;
Jim Laskey7075d6f2006-03-08 19:31:15 +00002161 case Intrinsic::dbg_stoppoint: {
2162 // If we use writeOperand directly we get a "u" suffix which is rejected
2163 // by gcc.
Jim Laskey580418e2006-03-23 18:08:29 +00002164 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey7075d6f2006-03-08 19:31:15 +00002165
2166 Out << "\n#line "
Jim Laskey580418e2006-03-23 18:08:29 +00002167 << SPI.getLine()
2168 << " \"" << SPI.getDirectory()
2169 << SPI.getFileName() << "\"\n";
Jim Laskey7075d6f2006-03-08 19:31:15 +00002170 return;
2171 }
Chris Lattner18ac3c82003-05-08 18:41:45 +00002172 }
2173 }
2174
Chris Lattner4394d512004-11-13 22:21:56 +00002175 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002176
Chris Lattner0c54d892006-05-23 23:39:48 +00002177 // If this is a call to a struct-return function, assign to the first
2178 // parameter instead of passing it to the call.
2179 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2180 if (isStructRet) {
2181 Out << "*(";
2182 writeOperand(I.getOperand(1));
2183 Out << ") = ";
2184 }
2185
Chris Lattnerfe673d92005-05-06 06:53:07 +00002186 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner4394d512004-11-13 22:21:56 +00002187
2188 const PointerType *PTy = cast<PointerType>(Callee->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002189 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner0c54d892006-05-23 23:39:48 +00002190
2191 if (!WroteCallee) {
2192 // If this is an indirect call to a struct return function, we need to cast
2193 // the pointer.
2194 bool NeedsCast = isStructRet && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002195
Chris Lattner0c54d892006-05-23 23:39:48 +00002196 // GCC is a real PITA. It does not permit codegening casts of functions to
2197 // function pointers if they are in a call (it generates a trap instruction
2198 // instead!). We work around this by inserting a cast to void* in between
2199 // the function and the function pointer cast. Unfortunately, we can't just
2200 // form the constant expression here, because the folder will immediately
2201 // nuke it.
2202 //
2203 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2204 // that void* and function pointers have the same size. :( To deal with this
2205 // in the common case, we handle casts where the number of arguments passed
2206 // match exactly.
2207 //
2208 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00002209 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00002210 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2211 NeedsCast = true;
2212 Callee = RF;
2213 }
2214
2215 if (NeedsCast) {
2216 // Ok, just cast the pointer type.
2217 Out << "((";
2218 if (!isStructRet)
2219 printType(Out, I.getCalledValue()->getType());
2220 else
2221 printStructReturnPointerFunctionType(Out,
2222 cast<PointerType>(I.getCalledValue()->getType()));
2223 Out << ")(void*)";
2224 }
2225 writeOperand(Callee);
2226 if (NeedsCast) Out << ')';
2227 }
2228
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002229 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002230
Chris Lattner4394d512004-11-13 22:21:56 +00002231 unsigned NumDeclaredParams = FTy->getNumParams();
2232
Chris Lattner0c54d892006-05-23 23:39:48 +00002233 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2234 unsigned ArgNo = 0;
2235 if (isStructRet) { // Skip struct return argument.
2236 ++AI;
2237 ++ArgNo;
2238 }
2239
2240 bool PrintedArg = false;
2241 for (; AI != AE; ++AI, ++ArgNo) {
2242 if (PrintedArg) Out << ", ";
2243 if (ArgNo < NumDeclaredParams &&
2244 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002245 Out << '(';
Chris Lattner0c54d892006-05-23 23:39:48 +00002246 printType(Out, FTy->getParamType(ArgNo));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002247 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00002248 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00002249 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00002250 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002251 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002252 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002253}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002254
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002255
2256//This converts the llvm constraint string to something gcc is expecting.
2257//This could be broken into a bunch of peices and spread accross the
2258//targets, but this information is only useful here.
2259//TODO: work out platform independent constraints and factor those out
2260static std::string InterpretConstraint(const std::string& target,
2261 InlineAsm::ConstraintInfo& c) {
2262
2263 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2264
2265 //catch numeric constraints
2266 if (c.Codes[0].find_first_not_of("0123456789") >= c.Codes[0].size())
2267 return c.Codes[0];
2268
2269 static const char* x86_table[] = {"{si}", "S",
2270 "{di}", "D",
2271 "{ax}", "a",
2272 "{cx}", "c",
2273 "q", "q",
2274 "r", "r",
2275 "m", "m",
2276 "{memory}", "memory",
2277 "{flags}", "",
2278 "{dirflag}", "",
2279 "{fpsr}", "",
2280 "{cc}", "cc"
2281 };
2282
2283 const char** table = 0;
2284 int tbl_len = 0;
2285 if (target == "i686-pc-linux-gnu") {
2286 table = x86_table;
2287 tbl_len = sizeof(x86_table) / sizeof(char*);
2288 }
2289 for (int i = 0; i < tbl_len && table; i += 2)
2290 if (c.Codes[0] == table[i])
2291 return table[i+1];
2292
2293 std::cerr << target << "\n";
2294 std::cerr << c.Codes[0] << "\n";
2295 assert(0 && "Unknown Asm Constraint");
2296 return "";
2297}
2298
2299//TODO: import logic from AsmPrinter.cpp
2300static std::string gccifyAsm(const std::string& target, std::string asmstr) {
2301 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2302 if (asmstr[i] == '\n')
2303 asmstr.replace(i, 1, "\\n");
2304 else if (asmstr[i] == '\t')
2305 asmstr.replace(i, 1, "\\t");
2306 else if (asmstr[i] == '$') {
2307 if (asmstr[i + 1] == '{') {
2308 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2309 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2310 std::string n = "%" +
2311 asmstr.substr(a + 1, b - a - 1) +
2312 asmstr.substr(i + 2, a - i - 2);
2313 asmstr.replace(i, b - i + 1, n);
2314 i += n.size() - 1;
2315 } else
2316 asmstr.replace(i, 1, "%");
2317 }
2318 else if (asmstr[i] == '%')//grr
2319 { asmstr.replace(i, 1, "%%"); ++i;}
2320
2321 return asmstr;
2322}
2323
2324void CWriter::visitInlineAsm(CallInst &CI) {
2325 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2326 const std::string& target = TheModule->getTargetTriple();
2327 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2328 std::vector<std::pair<std::string, Value*> > Input;
2329 std::vector<std::pair<std::string, Value*> > Output;
2330 std::string Clobber;
2331 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2332 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2333 E = Constraints.end(); I != E; ++I) {
2334 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2335 std::string c =
2336 InterpretConstraint(target, *I);
2337 switch(I->Type) {
2338 default:
2339 assert(0 && "Unknown asm constraint");
2340 break;
2341 case InlineAsm::isInput: {
2342 if (c.size()) {
2343 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2344 ++count; //consume arg
2345 }
2346 break;
2347 }
2348 case InlineAsm::isOutput: {
2349 if (c.size()) {
2350 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2351 count ? CI.getOperand(count) : &CI));
2352 ++count; //consume arg
2353 }
2354 break;
2355 }
2356 case InlineAsm::isClobber: {
2357 if (c.size())
2358 Clobber += ",\"" + c + "\"";
2359 break;
2360 }
2361 }
2362 }
2363
2364 //fix up the asm string for gcc
2365 std::string asmstr = gccifyAsm(target, as->getAsmString());
2366
2367 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2368 Out << " :";
2369 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2370 E = Output.end(); I != E; ++I) {
2371 Out << "\"" << I->first << "\"(";
2372 writeOperandRaw(I->second);
2373 Out << ")";
2374 if (I + 1 != E)
2375 Out << ",";
2376 }
2377 Out << "\n :";
2378 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2379 E = Input.end(); I != E; ++I) {
2380 Out << "\"" << I->first << "\"(";
2381 writeOperandRaw(I->second);
2382 Out << ")";
2383 if (I + 1 != E)
2384 Out << ",";
2385 }
2386 Out << "\n :" << Clobber.substr(1) << ")\n";
2387}
2388
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002389void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00002390 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002391}
2392
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002393void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002394 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002395 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002396 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002397 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002398 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002399 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002400 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002401 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002402 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002403 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002404}
2405
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002406void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerf31182a2004-02-13 23:18:48 +00002407 assert(0 && "lowerallocations pass didn't work!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002408}
2409
Chris Lattner23e90702003-11-25 20:49:55 +00002410void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2411 gep_type_iterator E) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002412 bool HasImplicitAddress = false;
2413 // If accessing a global value with no indexing, avoid *(&GV) syndrome
Reid Spencer3ed469c2006-11-02 20:25:50 +00002414 if (isa<GlobalValue>(Ptr)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002415 HasImplicitAddress = true;
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002416 } else if (isDirectAlloca(Ptr)) {
2417 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002418 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002419
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002420 if (I == E) {
2421 if (!HasImplicitAddress)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002422 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002423
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002424 writeOperandInternal(Ptr);
2425 return;
2426 }
2427
Chris Lattner23e90702003-11-25 20:49:55 +00002428 const Constant *CI = dyn_cast<Constant>(I.getOperand());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002429 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2430 Out << "(&";
2431
2432 writeOperandInternal(Ptr);
2433
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002434 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002435 Out << ')';
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002436 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2437 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002438
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002439 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2440 "Can only have implicit address with direct accessing");
2441
2442 if (HasImplicitAddress) {
2443 ++I;
Chris Lattner23e90702003-11-25 20:49:55 +00002444 } else if (CI && CI->isNullValue()) {
2445 gep_type_iterator TmpI = I; ++TmpI;
2446
Nick Hildenbrandte548f002002-09-25 20:29:26 +00002447 // Print out the -> operator if possible...
Chris Lattner23e90702003-11-25 20:49:55 +00002448 if (TmpI != E && isa<StructType>(*TmpI)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00002449 Out << (HasImplicitAddress ? "." : "->");
Reid Spencerb83eb642006-10-20 07:07:24 +00002450 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
Chris Lattner23e90702003-11-25 20:49:55 +00002451 I = ++TmpI;
2452 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002453 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002454
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002455 for (; I != E; ++I)
Chris Lattner23e90702003-11-25 20:49:55 +00002456 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002457 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002458 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002459 Out << '[';
Chris Lattner23e90702003-11-25 20:49:55 +00002460 writeOperand(I.getOperand());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002461 Out << ']';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002462 }
2463}
2464
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002465void CWriter::visitLoadInst(LoadInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002466 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002467 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002468 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002469 printType(Out, I.getType(), "volatile*");
2470 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002471 }
2472
Chris Lattner5dfe7672002-08-22 22:48:55 +00002473 writeOperand(I.getOperand(0));
Chris Lattner9d30e222005-02-14 16:47:52 +00002474
2475 if (I.isVolatile())
Misha Brukman23ba0c52005-03-08 00:26:08 +00002476 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002477}
2478
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002479void CWriter::visitStoreInst(StoreInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002480 Out << '*';
Chris Lattner9d30e222005-02-14 16:47:52 +00002481 if (I.isVolatile()) {
Chris Lattner8399e022005-02-15 05:52:14 +00002482 Out << "((";
Chris Lattnerb94388a2005-09-27 20:52:44 +00002483 printType(Out, I.getOperand(0)->getType(), " volatile*");
2484 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00002485 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00002486 writeOperand(I.getPointerOperand());
Misha Brukman23ba0c52005-03-08 00:26:08 +00002487 if (I.isVolatile()) Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002488 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002489 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002490}
2491
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002492void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002493 Out << '&';
Chris Lattner23e90702003-11-25 20:49:55 +00002494 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2495 gep_type_end(I));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002496}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002497
Chris Lattner4d45bd02003-10-18 05:57:43 +00002498void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00002499 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002500 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00002501 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00002502 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00002503 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00002504}
2505
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002506//===----------------------------------------------------------------------===//
2507// External Interface declaration
2508//===----------------------------------------------------------------------===//
2509
Chris Lattner1911fd42006-09-04 04:14:57 +00002510bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2511 std::ostream &o,
2512 CodeGenFileType FileType,
2513 bool Fast) {
Chris Lattner0431c962005-06-25 02:48:37 +00002514 if (FileType != TargetMachine::AssemblyFile) return true;
2515
Chris Lattner99c59e82004-05-23 21:23:35 +00002516 PM.add(createLowerGCPass());
Chris Lattnerf7fe4942005-03-03 01:04:50 +00002517 PM.add(createLowerAllocationsPass(true));
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002518 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00002519 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00002520 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00002521 PM.add(new CWriter(o));
Chris Lattnerf31182a2004-02-13 23:18:48 +00002522 return false;
2523}