blob: fb61651b3dc8a11751030b93cd4c34d7ec8b2457 [file] [log] [blame]
Reid Spencer76796932007-01-10 04:17:32 +00001//===-- CBackend.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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Reid Spencer78d033e2007-01-06 07:24:44 +000023#include "llvm/TypeSymbolTable.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"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000027#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/STLExtras.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000029#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000030#include "llvm/Analysis/FindUsedTypes.h"
31#include "llvm/Analysis/LoopInfo.h"
Anton Korobeynikove641b522009-08-05 09:29:56 +000032#include "llvm/Analysis/ValueTracking.h"
Gordon Henriksence224772008-01-07 01:30:38 +000033#include "llvm/CodeGen/Passes.h"
Chris Lattner30483732004-06-20 07:49:54 +000034#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000035#include "llvm/Transforms/Scalar.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000036#include "llvm/MC/MCAsmInfo.h"
Reid Spencer519e2392007-01-29 17:51:02 +000037#include "llvm/Target/TargetData.h"
Daniel Dunbar51b198a2009-07-15 20:24:03 +000038#include "llvm/Target/TargetRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000039#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000040#include "llvm/Support/CFG.h"
Torok Edwindac237e2009-07-08 20:53:28 +000041#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000042#include "llvm/Support/FormattedStream.h"
Chris Lattner23e90702003-11-25 20:49:55 +000043#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000044#include "llvm/Support/InstVisitor.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000045#include "llvm/Support/Mangler.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000046#include "llvm/Support/MathExtras.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000047#include "llvm/System/Host.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000048#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000049#include <algorithm>
Bill Wendling1a097e32006-12-07 23:41:45 +000050#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Daniel Dunbar0c795d62009-07-25 06:49:55 +000053extern "C" void LLVMInitializeCBackendTarget() {
54 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000055 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000056}
Douglas Gregor1555a232009-06-16 20:12:29 +000057
Dan Gohman844731a2008-05-13 00:00:25 +000058namespace {
Chris Lattnerf9a05322006-02-13 22:22:42 +000059 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
60 /// any unnamed structure types that are used by the program, and merges
61 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000062 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000063 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Devang Patel794fd752007-05-01 21:15:47 +000064 public:
Devang Patel19974732007-05-03 01:11:54 +000065 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +000066 CBackendNameAllUsedStructsAndMergeFunctions()
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 : ModulePass(&ID) {}
Chris Lattner68758072004-05-09 06:20:51 +000068 void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<FindUsedTypes>();
70 }
71
72 virtual const char *getPassName() const {
73 return "C backend type canonicalizer";
74 }
75
Chris Lattnerb12914b2004-09-20 04:48:05 +000076 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000077 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000078
Devang Patel19974732007-05-03 01:11:54 +000079 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +000080
Chris Lattner68758072004-05-09 06:20:51 +000081 /// CWriter - This class is the main chunk of code that converts an LLVM
82 /// module to a C translation unit.
83 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
David Greene71847812009-07-14 20:18:05 +000084 formatted_raw_ostream &Out;
Reid Spencer519e2392007-01-29 17:51:02 +000085 IntrinsicLowering *IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000086 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000087 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000088 const Module *TheModule;
Chris Lattneraf76e592009-08-22 20:48:53 +000089 const MCAsmInfo* TAsm;
Reid Spencer519e2392007-01-29 17:51:02 +000090 const TargetData* TD;
Chris Lattneredd8ce12003-05-03 03:14:35 +000091 std::map<const Type *, std::string> TypeNames;
Chris Lattneredd8ce12003-05-03 03:14:35 +000092 std::map<const ConstantFP *, unsigned> FPConstantMap;
Reid Spencer69f80a62007-04-12 21:00:45 +000093 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattnere05252b42008-03-02 08:07:24 +000094 std::set<const Argument*> ByValParams;
Chris Lattneraecc22a2008-10-22 04:53:16 +000095 unsigned FPCounter;
Owen Anderson52132bf2009-06-26 19:48:37 +000096 unsigned OpaqueCounter;
Chris Lattnerca1bafd2009-07-13 23:46:46 +000097 DenseMap<const Value*, unsigned> AnonValueNumbers;
98 unsigned NextAnonValueNumber;
Reid Spencer69f80a62007-04-12 21:00:45 +000099
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000100 public:
Devang Patel19974732007-05-03 01:11:54 +0000101 static char ID;
David Greene71847812009-07-14 20:18:05 +0000102 explicit CWriter(formatted_raw_ostream &o)
Dan Gohmanae73dc12008-09-04 17:05:41 +0000103 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000104 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
Chris Lattneraecc22a2008-10-22 04:53:16 +0000105 FPCounter = 0;
106 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000107
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000108 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000109
Chris Lattnercb3ad012004-05-09 20:41:32 +0000110 void getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.addRequired<LoopInfo>();
112 AU.setPreservesAll();
113 }
114
Chris Lattner68758072004-05-09 06:20:51 +0000115 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000116
Chris Lattner68758072004-05-09 06:20:51 +0000117 bool runOnFunction(Function &F) {
Chris Lattner9062d9a2009-04-17 00:26:12 +0000118 // Do not codegen any 'available_externally' functions at all, they have
119 // definitions outside the translation unit.
120 if (F.hasAvailableExternallyLinkage())
121 return false;
122
Chris Lattnercb3ad012004-05-09 20:41:32 +0000123 LI = &getAnalysis<LoopInfo>();
124
Chris Lattner3150e2d2004-12-05 06:49:44 +0000125 // Get rid of intrinsics we can't handle.
126 lowerIntrinsics(F);
127
Chris Lattner68758072004-05-09 06:20:51 +0000128 // Output all floating point constants that cannot be printed accurately.
129 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000130
Chris Lattner68758072004-05-09 06:20:51 +0000131 printFunction(F);
Chris Lattner68758072004-05-09 06:20:51 +0000132 return false;
133 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000134
Chris Lattner68758072004-05-09 06:20:51 +0000135 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000136 // Free memory...
Nuno Lopesbb6382e2009-01-13 23:35:49 +0000137 delete IL;
138 delete TD;
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000139 delete Mang;
Evan Cheng588c6f82008-01-11 09:12:49 +0000140 FPConstantMap.clear();
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000141 TypeNames.clear();
Evan Cheng588c6f82008-01-11 09:12:49 +0000142 ByValParams.clear();
Chris Lattnere05252b42008-03-02 08:07:24 +0000143 intrinsicPrototypesAlreadyGenerated.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000144 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000145 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000146
David Greene71847812009-07-14 20:18:05 +0000147 raw_ostream &printType(formatted_raw_ostream &Out,
148 const Type *Ty,
149 bool isSigned = false,
150 const std::string &VariableName = "",
151 bool IgnoreName = false,
152 const AttrListPtr &PAL = AttrListPtr());
Owen Andersoncb371882008-08-21 00:14:44 +0000153 std::ostream &printType(std::ostream &Out, const Type *Ty,
154 bool isSigned = false,
155 const std::string &VariableName = "",
156 bool IgnoreName = false,
Devang Patel05988662008-09-25 21:00:45 +0000157 const AttrListPtr &PAL = AttrListPtr());
David Greene71847812009-07-14 20:18:05 +0000158 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
159 const Type *Ty,
160 bool isSigned,
161 const std::string &NameSoFar = "");
Owen Andersoncb371882008-08-21 00:14:44 +0000162 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
163 bool isSigned,
164 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000165
David Greene71847812009-07-14 20:18:05 +0000166 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000167 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000168 const PointerType *Ty);
Chris Lattnere05252b42008-03-02 08:07:24 +0000169
170 /// writeOperandDeref - Print the result of dereferencing the specified
171 /// operand with '*'. This is equivalent to printing '*' then using
172 /// writeOperand, but avoids excess syntax in some cases.
173 void writeOperandDeref(Value *Operand) {
174 if (isAddressExposed(Operand)) {
175 // Already something with an address exposed.
176 writeOperandInternal(Operand);
177 } else {
178 Out << "*(";
179 writeOperand(Operand);
180 Out << ")";
181 }
182 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000183
Dan Gohman9f8d5712008-07-24 17:57:48 +0000184 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnere56d9462008-05-31 09:23:55 +0000185 void writeInstComputationInline(Instruction &I);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000186 void writeOperandInternal(Value *Operand, bool Static = false);
Reid Spencer1628cec2006-10-26 06:15:43 +0000187 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner5bda9e42007-09-15 06:51:03 +0000188 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000189 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000190
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +0000191 void writeMemoryAccess(Value *Operand, const Type *OperandType,
192 bool IsVolatile, unsigned Alignment);
193
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000194 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000195 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
196
Chris Lattnerc2421432004-05-09 04:30:20 +0000197 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000198
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000199 void printModule(Module *M);
Reid Spencer78d033e2007-01-06 07:24:44 +0000200 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman193c2352008-06-02 21:30:49 +0000201 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000202 void printFloatingPointConstants(Function &F);
Chris Lattneraecc22a2008-10-22 04:53:16 +0000203 void printFloatingPointConstants(const Constant *C);
Chris Lattner4cda8352002-08-20 16:55:48 +0000204 void printFunctionSignature(const Function *F, bool Prototype);
205
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000206 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000207 void printBasicBlock(BasicBlock *BB);
208 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000209
Reid Spencer3da59db2006-11-27 01:05:10 +0000210 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000211 void printConstant(Constant *CPV, bool Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000212 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000213 bool printConstExprCast(const ConstantExpr *CE, bool Static);
214 void printConstantArray(ConstantArray *CPA, bool Static);
215 void printConstantVector(ConstantVector *CV, bool Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000216
Chris Lattnere05252b42008-03-02 08:07:24 +0000217 /// isAddressExposed - Return true if the specified value's name needs to
218 /// have its address taken in order to get a C value of the correct type.
219 /// This happens for global variables, byval parameters, and direct allocas.
220 bool isAddressExposed(const Value *V) const {
221 if (const Argument *A = dyn_cast<Argument>(V))
222 return ByValParams.count(A);
223 return isa<GlobalVariable>(V) || isDirectAlloca(V);
224 }
225
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000226 // isInlinableInst - Attempt to inline instructions into their uses to build
227 // trees as much as possible. To do this, we have to consistently decide
228 // what is acceptable to inline, so that variable declarations don't get
229 // printed and an extra copy of the expr is not emitted.
230 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000231 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000232 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000233 // expressions. GCC generates horrible code if we don't.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000234 if (isa<CmpInst>(I))
235 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000236
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000237 // Must be an expression, must be used exactly once. If it is dead, we
238 // emit it inline where it would go.
Owen Anderson1d0be152009-08-13 21:58:54 +0000239 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000240 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman193c2352008-06-02 21:30:49 +0000241 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
242 isa<InsertValueInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000243 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000244 return false;
245
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000246 // Must not be used in inline asm, extractelement, or shufflevector.
247 if (I.hasOneUse()) {
248 const Instruction &User = cast<Instruction>(*I.use_back());
249 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
250 isa<ShuffleVectorInst>(User))
251 return false;
252 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000253
Reid Spencer555a0b12006-12-11 20:39:15 +0000254 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000255 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000256 }
257
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000258 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
259 // variables which are accessed with the & operator. This causes GCC to
260 // generate significantly better code than to emit alloca calls directly.
261 //
262 static const AllocaInst *isDirectAlloca(const Value *V) {
263 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
264 if (!AI) return false;
265 if (AI->isArrayAllocation())
266 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000267 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000268 return 0;
269 return AI;
270 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000271
272 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
273 static bool isInlineAsm(const Instruction& I) {
274 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
275 return true;
276 return false;
277 }
278
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000279 // Instruction visitation functions
280 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000281
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000282 void visitReturnInst(ReturnInst &I);
283 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000284 void visitSwitchInst(SwitchInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000285 void visitInvokeInst(InvokeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000286 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000287 }
288
289 void visitUnwindInst(UnwindInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000290 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000291 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000292 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000293
Chris Lattner84e66652003-05-03 07:11:00 +0000294 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000295 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000296 void visitICmpInst(ICmpInst &I);
297 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000298
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000299 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000300 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000301 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000302 void visitInlineAsm(CallInst &I);
Chris Lattner2299fec2008-03-02 08:29:41 +0000303 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000304
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000305 void visitAllocaInst(AllocaInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000306 void visitLoadInst (LoadInst &I);
307 void visitStoreInst (StoreInst &I);
308 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000309 void visitVAArgInst (VAArgInst &I);
Chris Lattner33a44d92008-03-02 03:52:39 +0000310
311 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner0452ed62008-03-02 03:57:08 +0000312 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000313 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000314
Dan Gohman193c2352008-06-02 21:30:49 +0000315 void visitInsertValueInst(InsertValueInst &I);
316 void visitExtractValueInst(ExtractValueInst &I);
317
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000318 void visitInstruction(Instruction &I) {
Torok Edwindac237e2009-07-08 20:53:28 +0000319#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000320 errs() << "C Writer does not know about " << I;
Torok Edwindac237e2009-07-08 20:53:28 +0000321#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000322 llvm_unreachable(0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000323 }
324
325 void outputLValue(Instruction *I) {
Bill Wendling145aad02007-02-23 22:45:08 +0000326 Out << " " << GetValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000327 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000328
329 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000330 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
331 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000332 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
333 unsigned Indent);
Chris Lattnere05252b42008-03-02 08:07:24 +0000334 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +0000335 gep_type_iterator E, bool Static);
Bill Wendling145aad02007-02-23 22:45:08 +0000336
337 std::string GetValueName(const Value *Operand);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000338 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000339}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000340
Devang Patel19974732007-05-03 01:11:54 +0000341char CWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000342
Chris Lattner68758072004-05-09 06:20:51 +0000343/// This method inserts names for any unnamed structure types that are used by
344/// the program, and removes names from structure types that are not used by the
345/// program.
346///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000347bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000348 // Get a set of types that are used by the program...
349 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000350
Chris Lattner68758072004-05-09 06:20:51 +0000351 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000352 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000353 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000354 TypeSymbolTable &TST = M.getTypeSymbolTable();
355 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000356 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000357 TypeSymbolTable::iterator I = TI++;
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000358
Dan Gohman193c2352008-06-02 21:30:49 +0000359 // If this isn't a struct or array type, remove it from our set of types
360 // to name. This simplifies emission later.
361 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
362 !isa<ArrayType>(I->second)) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000363 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000364 } else {
365 // If this is not used, remove it from the symbol table.
366 std::set<const Type *>::iterator UTI = UT.find(I->second);
367 if (UTI == UT.end())
368 TST.remove(I);
369 else
370 UT.erase(UTI); // Only keep one name for this type.
371 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000372 }
Chris Lattner68758072004-05-09 06:20:51 +0000373
374 // UT now contains types that are not named. Loop over it, naming
375 // structure types.
376 //
377 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000378 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000379 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
380 I != E; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +0000381 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
382 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000383 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000384 Changed = true;
385 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000386
387
388 // Loop over all external functions and globals. If we have two with
389 // identical names, merge them.
390 // FIXME: This code should disappear when we don't allow values with the same
391 // names when they have different types!
392 std::map<std::string, GlobalValue*> ExtSymbols;
393 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
394 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000395 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000396 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
397 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
398 if (!X.second) {
399 // Found a conflict, replace this global with the previous one.
400 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000401 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000402 GV->eraseFromParent();
403 Changed = true;
404 }
405 }
406 }
407 // Do the same for globals.
408 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
409 I != E;) {
410 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000411 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000412 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
413 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
414 if (!X.second) {
415 // Found a conflict, replace this global with the previous one.
416 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000417 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000418 GV->eraseFromParent();
419 Changed = true;
420 }
421 }
422 }
423
Chris Lattner68758072004-05-09 06:20:51 +0000424 return Changed;
425}
426
Chris Lattner0c54d892006-05-23 23:39:48 +0000427/// printStructReturnPointerFunctionType - This is like printType for a struct
428/// return type, except, instead of printing the type as void (*)(Struct*, ...)
429/// print it as "Struct (*)(...)", for struct return functions.
David Greene71847812009-07-14 20:18:05 +0000430void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000431 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000432 const PointerType *TheTy) {
433 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
434 std::stringstream FunctionInnards;
435 FunctionInnards << " (*) (";
436 bool PrintedType = false;
437
438 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
439 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000440 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000441 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000442 if (PrintedType)
443 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000444 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000445 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +0000446 assert(isa<PointerType>(ArgTy));
447 ArgTy = cast<PointerType>(ArgTy)->getElementType();
448 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000449 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000450 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000451 PrintedType = true;
452 }
453 if (FTy->isVarArg()) {
454 if (PrintedType)
455 FunctionInnards << ", ...";
456 } else if (!PrintedType) {
457 FunctionInnards << "void";
458 }
459 FunctionInnards << ')';
460 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000461 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +0000462 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000463}
464
Owen Andersoncb371882008-08-21 00:14:44 +0000465raw_ostream &
David Greene71847812009-07-14 20:18:05 +0000466CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
467 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000468 const std::string &NameSoFar) {
469 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
470 "Invalid type for printSimpleType");
471 switch (Ty->getTypeID()) {
472 case Type::VoidTyID: return Out << "void " << NameSoFar;
473 case Type::IntegerTyID: {
474 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
475 if (NumBits == 1)
476 return Out << "bool " << NameSoFar;
477 else if (NumBits <= 8)
478 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
479 else if (NumBits <= 16)
480 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
481 else if (NumBits <= 32)
482 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
483 else if (NumBits <= 64)
484 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
485 else {
486 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
487 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
488 }
489 }
490 case Type::FloatTyID: return Out << "float " << NameSoFar;
491 case Type::DoubleTyID: return Out << "double " << NameSoFar;
492 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
493 // present matches host 'long double'.
494 case Type::X86_FP80TyID:
495 case Type::PPC_FP128TyID:
496 case Type::FP128TyID: return Out << "long double " << NameSoFar;
497
498 case Type::VectorTyID: {
499 const VectorType *VTy = cast<VectorType>(Ty);
500 return printSimpleType(Out, VTy->getElementType(), isSigned,
501 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000502 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Andersoncb371882008-08-21 00:14:44 +0000503 }
504
505 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000506#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000507 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000508#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000509 llvm_unreachable(0);
Owen Andersoncb371882008-08-21 00:14:44 +0000510 }
511}
512
Reid Spencere4d87aa2006-12-23 06:05:41 +0000513std::ostream &
Reid Spencera54b7cb2007-01-12 07:05:14 +0000514CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000515 const std::string &NameSoFar) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000516 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000517 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000518 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000519 case Type::VoidTyID: return Out << "void " << NameSoFar;
520 case Type::IntegerTyID: {
521 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
522 if (NumBits == 1)
523 return Out << "bool " << NameSoFar;
524 else if (NumBits <= 8)
525 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
526 else if (NumBits <= 16)
527 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
528 else if (NumBits <= 32)
529 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000530 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000531 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000532 else {
533 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
534 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000535 }
536 }
537 case Type::FloatTyID: return Out << "float " << NameSoFar;
538 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000539 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
540 // present matches host 'long double'.
541 case Type::X86_FP80TyID:
542 case Type::PPC_FP128TyID:
543 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000544
545 case Type::VectorTyID: {
546 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000547 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000548 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000549 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000550 }
551
552 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000553#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000554 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000555#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000556 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000557 }
558}
Chris Lattner68758072004-05-09 06:20:51 +0000559
Chris Lattner83c57752002-08-19 22:17:53 +0000560// Pass the Type* and the variable name and this prints out the variable
561// declaration.
562//
David Greene71847812009-07-14 20:18:05 +0000563raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
564 const Type *Ty,
565 bool isSigned, const std::string &NameSoFar,
566 bool IgnoreName, const AttrListPtr &PAL) {
Owen Andersoncb371882008-08-21 00:14:44 +0000567 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
568 printSimpleType(Out, Ty, isSigned, NameSoFar);
569 return Out;
570 }
571
572 // Check to see if the type is named.
573 if (!IgnoreName || isa<OpaqueType>(Ty)) {
574 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
575 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
576 }
577
578 switch (Ty->getTypeID()) {
579 case Type::FunctionTyID: {
580 const FunctionType *FTy = cast<FunctionType>(Ty);
581 std::stringstream FunctionInnards;
582 FunctionInnards << " (" << NameSoFar << ") (";
583 unsigned Idx = 1;
584 for (FunctionType::param_iterator I = FTy->param_begin(),
585 E = FTy->param_end(); I != E; ++I) {
586 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000587 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Andersoncb371882008-08-21 00:14:44 +0000588 assert(isa<PointerType>(ArgTy));
589 ArgTy = cast<PointerType>(ArgTy)->getElementType();
590 }
591 if (I != FTy->param_begin())
592 FunctionInnards << ", ";
593 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000594 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000595 ++Idx;
596 }
597 if (FTy->isVarArg()) {
598 if (FTy->getNumParams())
599 FunctionInnards << ", ...";
600 } else if (!FTy->getNumParams()) {
601 FunctionInnards << "void";
602 }
603 FunctionInnards << ')';
604 std::string tstr = FunctionInnards.str();
605 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000606 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000607 return Out;
608 }
609 case Type::StructTyID: {
610 const StructType *STy = cast<StructType>(Ty);
611 Out << NameSoFar + " {\n";
612 unsigned Idx = 0;
613 for (StructType::element_iterator I = STy->element_begin(),
614 E = STy->element_end(); I != E; ++I) {
615 Out << " ";
616 printType(Out, *I, false, "field" + utostr(Idx++));
617 Out << ";\n";
618 }
619 Out << '}';
620 if (STy->isPacked())
621 Out << " __attribute__ ((packed))";
622 return Out;
623 }
624
625 case Type::PointerTyID: {
626 const PointerType *PTy = cast<PointerType>(Ty);
627 std::string ptrName = "*" + NameSoFar;
628
629 if (isa<ArrayType>(PTy->getElementType()) ||
630 isa<VectorType>(PTy->getElementType()))
631 ptrName = "(" + ptrName + ")";
632
633 if (!PAL.isEmpty())
634 // Must be a function ptr cast!
635 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
636 return printType(Out, PTy->getElementType(), false, ptrName);
637 }
638
639 case Type::ArrayTyID: {
640 const ArrayType *ATy = cast<ArrayType>(Ty);
641 unsigned NumElements = ATy->getNumElements();
642 if (NumElements == 0) NumElements = 1;
643 // Arrays are wrapped in structs to allow them to have normal
644 // value semantics (avoiding the array "decay").
645 Out << NameSoFar << " { ";
646 printType(Out, ATy->getElementType(), false,
647 "array[" + utostr(NumElements) + "]");
648 return Out << "; }";
649 }
650
651 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000652 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Andersoncb371882008-08-21 00:14:44 +0000653 assert(TypeNames.find(Ty) == TypeNames.end());
654 TypeNames[Ty] = TyName;
655 return Out << TyName << ' ' << NameSoFar;
656 }
657 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000658 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Andersoncb371882008-08-21 00:14:44 +0000659 }
660
661 return Out;
662}
663
664// Pass the Type* and the variable name and this prints out the variable
665// declaration.
666//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000667std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
Reid Spencer0ae96932007-01-07 03:24:48 +0000668 bool isSigned, const std::string &NameSoFar,
Devang Patel05988662008-09-25 21:00:45 +0000669 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000670 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000671 printSimpleType(Out, Ty, isSigned, NameSoFar);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000672 return Out;
673 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000674
Chris Lattner83c57752002-08-19 22:17:53 +0000675 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000676 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000677 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000678 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000679 }
Chris Lattner83c57752002-08-19 22:17:53 +0000680
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000681 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000682 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000683 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000684 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000685 FunctionInnards << " (" << NameSoFar << ") (";
Reid Spencer0ae96932007-01-07 03:24:48 +0000686 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +0000687 for (FunctionType::param_iterator I = FTy->param_begin(),
688 E = FTy->param_end(); I != E; ++I) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000689 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000690 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000691 assert(isa<PointerType>(ArgTy));
692 ArgTy = cast<PointerType>(ArgTy)->getElementType();
693 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000694 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000695 FunctionInnards << ", ";
Evan Cheng7723ab32008-01-12 18:53:07 +0000696 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000697 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Reid Spencer0ae96932007-01-07 03:24:48 +0000698 ++Idx;
Chris Lattner83c57752002-08-19 22:17:53 +0000699 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000700 if (FTy->isVarArg()) {
701 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000702 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000703 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000704 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000705 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000706 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000707 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000708 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000709 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000710 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000711 }
712 case Type::StructTyID: {
713 const StructType *STy = cast<StructType>(Ty);
714 Out << NameSoFar + " {\n";
715 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000716 for (StructType::element_iterator I = STy->element_begin(),
717 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000718 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000719 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000720 Out << ";\n";
721 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000722 Out << '}';
723 if (STy->isPacked())
724 Out << " __attribute__ ((packed))";
725 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000726 }
Chris Lattner83c57752002-08-19 22:17:53 +0000727
728 case Type::PointerTyID: {
729 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000730 std::string ptrName = "*" + NameSoFar;
731
Robert Bocchinob78e8382006-01-20 20:43:57 +0000732 if (isa<ArrayType>(PTy->getElementType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +0000733 isa<VectorType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000734 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000735
Chris Lattner58d74912008-03-12 17:45:29 +0000736 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000737 // Must be a function ptr cast!
738 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000739 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000740 }
Chris Lattner83c57752002-08-19 22:17:53 +0000741
742 case Type::ArrayTyID: {
743 const ArrayType *ATy = cast<ArrayType>(Ty);
744 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000745 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000746 // Arrays are wrapped in structs to allow them to have normal
747 // value semantics (avoiding the array "decay").
748 Out << NameSoFar << " { ";
749 printType(Out, ATy->getElementType(), false,
750 "array[" + utostr(NumElements) + "]");
751 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000752 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000753
754 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000755 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000756 assert(TypeNames.find(Ty) == TypeNames.end());
757 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000758 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000759 }
Chris Lattner83c57752002-08-19 22:17:53 +0000760 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000761 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000762 }
763
764 return Out;
765}
766
Dan Gohman9f8d5712008-07-24 17:57:48 +0000767void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000768
769 // As a special case, print the array as a string if it is an array of
770 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000771 //
Chris Lattner6d492922002-08-19 21:32:41 +0000772 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000773 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
774 ETy == Type::getInt8Ty(CPA->getContext()));
Chris Lattner6d492922002-08-19 21:32:41 +0000775
776 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000777 if (isString && (CPA->getNumOperands() == 0 ||
778 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000779 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000780
Chris Lattner6d492922002-08-19 21:32:41 +0000781 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000782 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000783 // Keep track of whether the last number was a hexadecimal escape
784 bool LastWasHex = false;
785
Chris Lattner6d492922002-08-19 21:32:41 +0000786 // Do not include the last character, which we know is null
787 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000788 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000789
Chris Lattner02da6c02003-06-16 12:09:09 +0000790 // Print it out literally if it is a printable character. The only thing
791 // to be careful about is when the last letter output was a hex escape
792 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000793 // explicitly (the C compiler thinks it is a continuation of the previous
794 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000795 //
796 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
797 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000798 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000799 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000800 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000801 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000802 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000803 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000804 switch (C) {
805 case '\n': Out << "\\n"; break;
806 case '\t': Out << "\\t"; break;
807 case '\r': Out << "\\r"; break;
808 case '\v': Out << "\\v"; break;
809 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000810 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000811 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000812 default:
813 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000814 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
815 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
816 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000817 break;
818 }
819 }
820 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000821 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000822 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000823 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000824 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000825 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000826 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000827 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
828 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000829 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000830 }
831 }
832 Out << " }";
833 }
834}
835
Dan Gohman9f8d5712008-07-24 17:57:48 +0000836void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000837 Out << '{';
838 if (CP->getNumOperands()) {
839 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000840 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000841 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
842 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000843 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000844 }
845 }
846 Out << " }";
847}
848
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000849// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
850// textually as a double (rather than as a reference to a stack-allocated
851// variable). We decide this by converting CFP to a string and back into a
852// double, and then checking whether the conversion results in a bit-equal
853// double to the original value of CFP. This depends on us and the target C
854// compiler agreeing on the conversion process (which is pretty likely since we
855// only deal in IEEE FP).
856//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000857static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000858 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000859 // Do long doubles in hex for now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000860 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
861 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000862 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000863 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000864 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000865 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000866#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000867 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000868 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000869 if (!strncmp(Buffer, "0x", 2) ||
870 !strncmp(Buffer, "-0x", 3) ||
871 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000872 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000873 return false;
874#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000875 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000876
877 while (StrVal[0] == ' ')
878 StrVal.erase(StrVal.begin());
879
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000880 // Check to make sure that the stringized number is not some string like "Inf"
881 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000882 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
883 ((StrVal[0] == '-' || StrVal[0] == '+') &&
884 (StrVal[1] >= '0' && StrVal[1] <= '9')))
885 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000886 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000887 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000888#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000889}
Chris Lattner6d492922002-08-19 21:32:41 +0000890
Reid Spencer3da59db2006-11-27 01:05:10 +0000891/// Print out the casting for a cast operation. This does the double casting
892/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000893/// @brief Print a cast
894void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000895 // Print the destination type cast
896 switch (opc) {
897 case Instruction::UIToFP:
898 case Instruction::SIToFP:
899 case Instruction::IntToPtr:
900 case Instruction::Trunc:
901 case Instruction::BitCast:
902 case Instruction::FPExt:
903 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
904 Out << '(';
905 printType(Out, DstTy);
906 Out << ')';
907 break;
908 case Instruction::ZExt:
909 case Instruction::PtrToInt:
910 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
911 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000912 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000913 Out << ')';
914 break;
915 case Instruction::SExt:
916 case Instruction::FPToSI: // For these, make sure we get a signed dest
917 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000918 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000919 Out << ')';
920 break;
921 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000922 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000923 }
924
925 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000926 switch (opc) {
927 case Instruction::UIToFP:
928 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000929 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000930 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000931 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000932 break;
933 case Instruction::SIToFP:
934 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000935 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000936 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000937 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000938 break;
939 case Instruction::IntToPtr:
940 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000941 // Avoid "cast to pointer from integer of different size" warnings
942 Out << "(unsigned long)";
943 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000944 case Instruction::Trunc:
945 case Instruction::BitCast:
946 case Instruction::FPExt:
947 case Instruction::FPTrunc:
948 case Instruction::FPToSI:
949 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000950 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000951 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000952 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000953 break;
954 }
955}
956
Chris Lattner6d492922002-08-19 21:32:41 +0000957// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000958void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000959 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
960 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000961 case Instruction::Trunc:
962 case Instruction::ZExt:
963 case Instruction::SExt:
964 case Instruction::FPTrunc:
965 case Instruction::FPExt:
966 case Instruction::UIToFP:
967 case Instruction::SIToFP:
968 case Instruction::FPToUI:
969 case Instruction::FPToSI:
970 case Instruction::PtrToInt:
971 case Instruction::IntToPtr:
972 case Instruction::BitCast:
973 Out << "(";
974 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +0000975 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000976 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Reid Spencercee7ba32007-05-02 02:17:41 +0000977 // Make sure we really sext from bool here by subtracting from 0
978 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +0000979 }
Dan Gohman9f8d5712008-07-24 17:57:48 +0000980 printConstant(CE->getOperand(0), Static);
Owen Anderson1d0be152009-08-13 21:58:54 +0000981 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Chris Lattner72623362007-05-03 02:57:13 +0000982 (CE->getOpcode() == Instruction::Trunc ||
983 CE->getOpcode() == Instruction::FPToUI ||
984 CE->getOpcode() == Instruction::FPToSI ||
985 CE->getOpcode() == Instruction::PtrToInt)) {
986 // Make sure we really truncate to bool here by anding with 1
987 Out << "&1u";
988 }
989 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000990 return;
Chris Lattner72623362007-05-03 02:57:13 +0000991
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000992 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +0000993 Out << "(";
994 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +0000995 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +0000996 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000997 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +0000998 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000999 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001000 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001001 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001002 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001003 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001004 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001005 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +00001006 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001007 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001008 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001009 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001010 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +00001011 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001012 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001013 case Instruction::SDiv:
1014 case Instruction::UDiv:
1015 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001016 case Instruction::URem:
1017 case Instruction::SRem:
1018 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001019 case Instruction::And:
1020 case Instruction::Or:
1021 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001022 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001023 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001024 case Instruction::LShr:
1025 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +00001026 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001027 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001028 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +00001029 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +00001030 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001031 case Instruction::Add:
1032 case Instruction::FAdd: Out << " + "; break;
1033 case Instruction::Sub:
1034 case Instruction::FSub: Out << " - "; break;
1035 case Instruction::Mul:
1036 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001037 case Instruction::URem:
1038 case Instruction::SRem:
1039 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001040 case Instruction::UDiv:
1041 case Instruction::SDiv:
1042 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001043 case Instruction::And: Out << " & "; break;
1044 case Instruction::Or: Out << " | "; break;
1045 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001046 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001047 case Instruction::LShr:
1048 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001049 case Instruction::ICmp:
1050 switch (CE->getPredicate()) {
1051 case ICmpInst::ICMP_EQ: Out << " == "; break;
1052 case ICmpInst::ICMP_NE: Out << " != "; break;
1053 case ICmpInst::ICMP_SLT:
1054 case ICmpInst::ICMP_ULT: Out << " < "; break;
1055 case ICmpInst::ICMP_SLE:
1056 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1057 case ICmpInst::ICMP_SGT:
1058 case ICmpInst::ICMP_UGT: Out << " > "; break;
1059 case ICmpInst::ICMP_SGE:
1060 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001061 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001062 }
1063 break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001064 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +00001065 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001066 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1067 if (NeedsClosingParens)
1068 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001069 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001070 return;
Reid Spencer72ddc212006-10-26 06:17:40 +00001071 }
Reid Spencerb801a272007-01-08 06:58:32 +00001072 case Instruction::FCmp: {
1073 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001074 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +00001075 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1076 Out << "0";
1077 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1078 Out << "1";
1079 else {
1080 const char* op = 0;
1081 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001082 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00001083 case FCmpInst::FCMP_ORD: op = "ord"; break;
1084 case FCmpInst::FCMP_UNO: op = "uno"; break;
1085 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1086 case FCmpInst::FCMP_UNE: op = "une"; break;
1087 case FCmpInst::FCMP_ULT: op = "ult"; break;
1088 case FCmpInst::FCMP_ULE: op = "ule"; break;
1089 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1090 case FCmpInst::FCMP_UGE: op = "uge"; break;
1091 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1092 case FCmpInst::FCMP_ONE: op = "one"; break;
1093 case FCmpInst::FCMP_OLT: op = "olt"; break;
1094 case FCmpInst::FCMP_OLE: op = "ole"; break;
1095 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1096 case FCmpInst::FCMP_OGE: op = "oge"; break;
1097 }
1098 Out << "llvm_fcmp_" << op << "(";
1099 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1100 Out << ", ";
1101 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1102 Out << ")";
1103 }
1104 if (NeedsClosingParens)
1105 Out << "))";
1106 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +00001107 return;
Reid Spencerb801a272007-01-08 06:58:32 +00001108 }
Chris Lattner6d492922002-08-19 21:32:41 +00001109 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001110#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001111 errs() << "CWriter Error: Unhandled constant expression: "
Bill Wendlingf5da1332006-12-07 22:21:48 +00001112 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001113#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001114 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001115 }
Dan Gohman17dab192008-05-23 16:57:00 +00001116 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +00001117 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001118 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001119 Out << ")/*UNDEF*/";
1120 if (!isa<VectorType>(CPV->getType())) {
1121 Out << "0)";
1122 } else {
1123 Out << "{})";
1124 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001125 return;
Chris Lattner6d492922002-08-19 21:32:41 +00001126 }
1127
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001128 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1129 const Type* Ty = CI->getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001130 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001131 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson1d0be152009-08-13 21:58:54 +00001132 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001133 Out << CI->getZExtValue() << 'u';
1134 else if (Ty->getPrimitiveSizeInBits() > 32)
1135 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001136 else {
1137 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001138 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001139 if (CI->isMinValue(true))
1140 Out << CI->getZExtValue() << 'u';
1141 else
1142 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001143 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001144 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001145 return;
1146 }
1147
1148 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001149 case Type::FloatTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001150 case Type::DoubleTyID:
1151 case Type::X86_FP80TyID:
1152 case Type::PPC_FP128TyID:
1153 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001154 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001155 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001156 if (I != FPConstantMap.end()) {
1157 // Because of FP precision problems we must load from a stack allocated
1158 // value that holds the value in hex.
Owen Anderson1d0be152009-08-13 21:58:54 +00001159 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1160 "float" :
1161 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1162 "double" :
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001163 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001164 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001165 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001166 double V;
Owen Anderson1d0be152009-08-13 21:58:54 +00001167 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001168 V = FPC->getValueAPF().convertToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +00001169 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001170 V = FPC->getValueAPF().convertToDouble();
1171 else {
1172 // Long double. Convert the number to double, discarding precision.
1173 // This is not awesome, but it at least makes the CBE output somewhat
1174 // useful.
1175 APFloat Tmp = FPC->getValueAPF();
1176 bool LosesInfo;
1177 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1178 V = Tmp.convertToDouble();
1179 }
1180
Dale Johannesen43421b32007-09-06 18:13:44 +00001181 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001182 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001183
Dale Johannesen43421b32007-09-06 18:13:44 +00001184 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001185 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1186 // it's 0x7ff4.
1187 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001188 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001189
1190 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001191 char Buffer[100];
1192
Dale Johannesen43421b32007-09-06 18:13:44 +00001193 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001194 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001195
1196 std::string Num(&Buffer[0], &Buffer[6]);
1197 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1198
Owen Anderson1d0be152009-08-13 21:58:54 +00001199 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Brian Gaeke8a702e82004-08-25 19:00:42 +00001200 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1201 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001202 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001203 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1204 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001205 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001206 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001207 if (V < 0) Out << '-';
Owen Anderson1d0be152009-08-13 21:58:54 +00001208 Out << "LLVM_INF" <<
1209 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Brian Gaeke8a702e82004-08-25 19:00:42 +00001210 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001211 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001212 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001213#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001214 // Print out the constant as a floating point number.
1215 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001216 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001217 Num = Buffer;
1218#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001219 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001220#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001221 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001222 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001223 }
1224 break;
1225 }
Chris Lattner6d492922002-08-19 21:32:41 +00001226
1227 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001228 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001229 if (!Static) {
1230 Out << "(";
1231 printType(Out, CPV->getType());
1232 Out << ")";
1233 }
Dan Gohman193c2352008-06-02 21:30:49 +00001234 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001235 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001236 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001237 } else {
1238 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001239 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001240 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001241 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001242 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001243 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001244 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001245 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1246 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001247 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001248 }
1249 }
1250 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001251 }
Dan Gohman193c2352008-06-02 21:30:49 +00001252 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001253 break;
1254
Reid Spencer9d6565a2007-02-15 02:26:10 +00001255 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001256 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001257 if (!Static) {
1258 Out << "(";
1259 printType(Out, CPV->getType());
1260 Out << ")";
1261 }
Chris Lattner939732a2008-03-02 05:46:57 +00001262 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001263 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001264 } else {
1265 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1266 const VectorType *VT = cast<VectorType>(CPV->getType());
1267 Out << "{ ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001268 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001269 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001270 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001271 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001272 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001273 }
1274 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001275 }
1276 break;
1277
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001278 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001279 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001280 if (!Static) {
1281 Out << "(";
1282 printType(Out, CPV->getType());
1283 Out << ")";
1284 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001285 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001286 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001287 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001288 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001289 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001290 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001291 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1292 Out << ", ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001293 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001294 }
Chris Lattner6d492922002-08-19 21:32:41 +00001295 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001296 Out << " }";
1297 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001298 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001299 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001300 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001301 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001302 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1303 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001304 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001305 }
1306 }
1307 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001308 }
Chris Lattner6d492922002-08-19 21:32:41 +00001309 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001310
1311 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001312 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001313 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001314 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001315 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001316 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001317 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001318 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001319 break;
1320 }
1321 // FALL THROUGH
1322 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001323#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001324 errs() << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001325#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001326 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001327 }
1328}
1329
Reid Spencer1628cec2006-10-26 06:15:43 +00001330// Some constant expressions need to be casted back to the original types
1331// because their operands were casted to the expected type. This function takes
1332// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001333bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001334 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001335 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001336 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001337 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001338 case Instruction::Add:
1339 case Instruction::Sub:
1340 case Instruction::Mul:
1341 // We need to cast integer arithmetic so that it is always performed
1342 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001343 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001344 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001345 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001346 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001347 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001348 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001349 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001350 Ty = CE->getType();
1351 NeedsExplicitCast = true;
1352 TypeIsSigned = true;
1353 break;
1354 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001355 case Instruction::Trunc:
1356 case Instruction::FPTrunc:
1357 case Instruction::FPExt:
1358 case Instruction::UIToFP:
1359 case Instruction::SIToFP:
1360 case Instruction::FPToUI:
1361 case Instruction::FPToSI:
1362 case Instruction::PtrToInt:
1363 case Instruction::IntToPtr:
1364 case Instruction::BitCast:
1365 Ty = CE->getType();
1366 NeedsExplicitCast = true;
1367 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001368 default: break;
1369 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001370 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001371 Out << "((";
Owen Anderson1d0be152009-08-13 21:58:54 +00001372 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001373 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001374 else
Reid Spencer251f2142007-01-09 17:09:09 +00001375 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001376 Out << ")(";
1377 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001378 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001379}
1380
1381// Print a constant assuming that it is the operand for a given Opcode. The
1382// opcodes that care about sign need to cast their operands to the expected
1383// type before the operation proceeds. This function does the casting.
1384void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1385
1386 // Extract the operand's type, we'll need it.
1387 const Type* OpTy = CPV->getType();
1388
1389 // Indicate whether to do the cast or not.
1390 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001391 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001392
1393 // Based on the Opcode for which this Constant is being written, determine
1394 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001395 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1396 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001397 switch (Opcode) {
1398 default:
1399 // for most instructions, it doesn't matter
1400 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001401 case Instruction::Add:
1402 case Instruction::Sub:
1403 case Instruction::Mul:
1404 // We need to cast integer arithmetic so that it is always performed
1405 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001406 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001407 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001408 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001409 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001410 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001411 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001412 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001413 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001414 shouldCast = true;
1415 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001416 break;
1417 }
1418
Reid Spencer3da59db2006-11-27 01:05:10 +00001419 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001420 // operand.
1421 if (shouldCast) {
1422 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001423 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001424 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001425 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001426 Out << ")";
1427 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001428 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001429}
1430
Bill Wendling145aad02007-02-23 22:45:08 +00001431std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001432 // Mangle globals with the standard mangler interface for LLC compatibility.
1433 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001434 return Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001435
1436 std::string Name = Operand->getName();
1437
1438 if (Name.empty()) { // Assign unique names to local temporaries.
1439 unsigned &No = AnonValueNumbers[Operand];
1440 if (No == 0)
1441 No = ++NextAnonValueNumber;
1442 Name = "tmp__" + utostr(No);
1443 }
1444
1445 std::string VarName;
1446 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001447
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001448 for (std::string::iterator I = Name.begin(), E = Name.end();
1449 I != E; ++I) {
1450 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001451
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001452 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1453 (ch >= '0' && ch <= '9') || ch == '_')) {
1454 char buffer[5];
1455 sprintf(buffer, "_%x_", ch);
1456 VarName += buffer;
1457 } else
1458 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001459 }
1460
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001461 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001462}
1463
Chris Lattnere56d9462008-05-31 09:23:55 +00001464/// writeInstComputationInline - Emit the computation for the specified
1465/// instruction inline, with no destination provided.
1466void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001467 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1468 // Validate this.
1469 const Type *Ty = I.getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001470 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1471 Ty!=Type::getInt8Ty(I.getContext()) &&
1472 Ty!=Type::getInt16Ty(I.getContext()) &&
1473 Ty!=Type::getInt32Ty(I.getContext()) &&
1474 Ty!=Type::getInt64Ty(I.getContext()))) {
Torok Edwindac237e2009-07-08 20:53:28 +00001475 llvm_report_error("The C backend does not currently support integer "
1476 "types of widths other than 1, 8, 16, 32, 64.\n"
1477 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001478 }
1479
Chris Lattnere56d9462008-05-31 09:23:55 +00001480 // If this is a non-trivial bool computation, make sure to truncate down to
1481 // a 1 bit value. This is important because we want "add i1 x, y" to return
1482 // "0" when x and y are true, not "2" for example.
1483 bool NeedBoolTrunc = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00001484 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1485 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnere56d9462008-05-31 09:23:55 +00001486 NeedBoolTrunc = true;
1487
1488 if (NeedBoolTrunc)
1489 Out << "((";
1490
1491 visit(I);
1492
1493 if (NeedBoolTrunc)
1494 Out << ")&1)";
1495}
1496
1497
Dan Gohman9f8d5712008-07-24 17:57:48 +00001498void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001499 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001500 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001501 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001502 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001503 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001504 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001505 return;
1506 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001507
Reid Spencer518310c2004-07-18 00:44:37 +00001508 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001509
1510 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001511 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001512 else
1513 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001514}
1515
Dan Gohman9f8d5712008-07-24 17:57:48 +00001516void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001517 bool isAddressImplicit = isAddressExposed(Operand);
1518 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001519 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001520
Dan Gohman9f8d5712008-07-24 17:57:48 +00001521 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001522
Chris Lattnere05252b42008-03-02 08:07:24 +00001523 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001524 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001525}
1526
Reid Spencer1628cec2006-10-26 06:15:43 +00001527// Some instructions need to have their result value casted back to the
1528// original types because their operands were casted to the expected type.
1529// This function takes care of detecting that case and printing the cast
1530// for the Instruction.
1531bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001532 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001533 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001534 case Instruction::Add:
1535 case Instruction::Sub:
1536 case Instruction::Mul:
1537 // We need to cast integer arithmetic so that it is always performed
1538 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001539 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001540 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001541 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001542 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001543 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001544 Out << ")(";
1545 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001546 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001547 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001548 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001549 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001550 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001551 Out << ")(";
1552 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001553 default: break;
1554 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001555 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001556}
1557
1558// Write the operand with a cast to another type based on the Opcode being used.
1559// This will be used in cases where an instruction has specific type
1560// requirements (usually signedness) for its operands.
1561void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1562
1563 // Extract the operand's type, we'll need it.
1564 const Type* OpTy = Operand->getType();
1565
1566 // Indicate whether to do the cast or not.
1567 bool shouldCast = false;
1568
Reid Spencere4d87aa2006-12-23 06:05:41 +00001569 // Indicate whether the cast should be to a signed type or not.
1570 bool castIsSigned = false;
1571
Reid Spencer1628cec2006-10-26 06:15:43 +00001572 // Based on the Opcode for which this Operand is being written, determine
1573 // the new type to which the operand should be casted by setting the value
1574 // of OpTy. If we change OpTy, also set shouldCast to true.
1575 switch (Opcode) {
1576 default:
1577 // for most instructions, it doesn't matter
1578 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001579 case Instruction::Add:
1580 case Instruction::Sub:
1581 case Instruction::Mul:
1582 // We need to cast integer arithmetic so that it is always performed
1583 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001584 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001585 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001586 case Instruction::URem: // Cast to unsigned first
1587 shouldCast = true;
1588 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001589 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001590 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001591 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001592 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001593 case Instruction::SRem: // Cast to signed first
1594 shouldCast = true;
1595 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001596 break;
1597 }
1598
1599 // Write out the casted operand if we should, otherwise just write the
1600 // operand.
1601 if (shouldCast) {
1602 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001603 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001604 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001605 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001606 Out << ")";
1607 } else
1608 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001609}
Reid Spencer1628cec2006-10-26 06:15:43 +00001610
Reid Spencere4d87aa2006-12-23 06:05:41 +00001611// Write the operand with a cast to another type based on the icmp predicate
1612// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001613void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1614 // This has to do a cast to ensure the operand has the right signedness.
1615 // Also, if the operand is a pointer, we make sure to cast to an integer when
1616 // doing the comparison both for signedness and so that the C compiler doesn't
1617 // optimize things like "p < NULL" to false (p may contain an integer value
1618 // f.e.).
1619 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001620
1621 // Write out the casted operand if we should, otherwise just write the
1622 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001623 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001624 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001625 return;
1626 }
1627
1628 // Should this be a signed comparison? If so, convert to signed.
Nick Lewycky4a134af2009-10-25 05:20:17 +00001629 bool castIsSigned = Cmp.isSigned();
Chris Lattner5bda9e42007-09-15 06:51:03 +00001630
1631 // If the operand was a pointer, convert to a large integer type.
1632 const Type* OpTy = Operand->getType();
1633 if (isa<PointerType>(OpTy))
Owen Anderson1d0be152009-08-13 21:58:54 +00001634 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner5bda9e42007-09-15 06:51:03 +00001635
1636 Out << "((";
1637 printSimpleType(Out, OpTy, castIsSigned);
1638 Out << ")";
1639 writeOperand(Operand);
1640 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001641}
1642
Chris Lattner41488192003-06-28 17:15:12 +00001643// generateCompilerSpecificCode - This is where we add conditional compilation
1644// directives to cater to specific compilers as need be.
1645//
David Greene71847812009-07-14 20:18:05 +00001646static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001647 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001648 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001649 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001650 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001651 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001652 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001653 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001654 << "extern void *__builtin_alloca(unsigned long);\n"
1655 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001656 << "#define longjmp _longjmp\n"
1657 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001658 << "#elif defined(__sun__)\n"
1659 << "#if defined(__sparcv9)\n"
1660 << "extern void *__builtin_alloca(unsigned long);\n"
1661 << "#else\n"
1662 << "extern void *__builtin_alloca(unsigned int);\n"
1663 << "#endif\n"
1664 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001665 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001666 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001667 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001668 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001669 << "#define alloca(x) _alloca(x)\n"
1670 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001671 << "#include <alloca.h>\n"
1672 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001673
1674 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1675 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001676 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001677 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001678 << "#endif\n\n";
1679
Brian Gaeke27f7a712003-12-11 00:24:36 +00001680 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1681 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1682 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1683 << "#elif defined(__GNUC__)\n"
1684 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1685 << "#else\n"
1686 << "#define __EXTERNAL_WEAK__\n"
1687 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001688
1689 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1690 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1691 << "#define __ATTRIBUTE_WEAK__\n"
1692 << "#elif defined(__GNUC__)\n"
1693 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1694 << "#else\n"
1695 << "#define __ATTRIBUTE_WEAK__\n"
1696 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001697
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001698 // Add hidden visibility support. FIXME: APPLE_CC?
1699 Out << "#if defined(__GNUC__)\n"
1700 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1701 << "#endif\n\n";
1702
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001703 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1704 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001705 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001706 // double __builtin_nan (const char *str)
1707 //
1708 // This is an implementation of the ISO C99 function nan.
1709 //
1710 // Since ISO C99 defines this function in terms of strtod, which we do
1711 // not implement, a description of the parsing is in order. The string is
1712 // parsed as by strtol; that is, the base is recognized by leading 0 or
1713 // 0x prefixes. The number parsed is placed in the significand such that
1714 // the least significant bit of the number is at the least significant
1715 // bit of the significand. The number is truncated to fit the significand
1716 // field provided. The significand is forced to be a quiet NaN.
1717 //
1718 // This function, if given a string literal, is evaluated early enough
1719 // that it is considered a compile-time constant.
1720 //
1721 // float __builtin_nanf (const char *str)
1722 //
1723 // Similar to __builtin_nan, except the return type is float.
1724 //
1725 // double __builtin_inf (void)
1726 //
1727 // Similar to __builtin_huge_val, except a warning is generated if the
1728 // target floating-point format does not support infinities. This
1729 // function is suitable for implementing the ISO C99 macro INFINITY.
1730 //
1731 // float __builtin_inff (void)
1732 //
1733 // Similar to __builtin_inf, except the return type is float.
1734 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001735 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1736 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1737 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1738 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1739 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1740 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001741 << "#define LLVM_PREFETCH(addr,rw,locality) "
1742 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001743 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1744 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001745 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001746 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001747 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1748 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1749 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1750 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1751 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1752 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001753 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001754 << "#define __ATTRIBUTE_CTOR__\n"
1755 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001756 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001757 << "#endif\n\n";
Chris Lattner40c1b662007-05-13 22:19:27 +00001758
1759 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1760 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1761 << "#define __builtin_stack_restore(X) /* noop */\n"
1762 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001763
Dan Gohman271515a2008-04-02 23:52:49 +00001764 // Output typedefs for 128-bit integers. If these are needed with a
1765 // 32-bit target or with a C compiler that doesn't support mode(TI),
1766 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001767 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1768 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1769 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1770 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001771
Chris Lattner50a8a172005-05-06 06:58:42 +00001772 // Output target-specific code that should be inserted into main.
1773 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001774}
1775
Chris Lattner9a571ba2006-03-07 22:58:23 +00001776/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1777/// the StaticTors set.
1778static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1779 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1780 if (!InitList) return;
1781
1782 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1783 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1784 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1785
1786 if (CS->getOperand(1)->isNullValue())
1787 return; // Found a null terminator, exit printing.
1788 Constant *FP = CS->getOperand(1);
1789 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001790 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001791 FP = CE->getOperand(0);
1792 if (Function *F = dyn_cast<Function>(FP))
1793 StaticTors.insert(F);
1794 }
1795}
1796
1797enum SpecialGlobalClass {
1798 NotSpecial = 0,
1799 GlobalCtors, GlobalDtors,
1800 NotPrinted
1801};
1802
1803/// getGlobalVariableClass - If this is a global that is specially recognized
1804/// by LLVM, return a code that indicates how we should handle it.
1805static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1806 // If this is a global ctors/dtors list, handle it now.
1807 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1808 if (GV->getName() == "llvm.global_ctors")
1809 return GlobalCtors;
1810 else if (GV->getName() == "llvm.global_dtors")
1811 return GlobalDtors;
1812 }
1813
1814 // Otherwise, it it is other metadata, don't print it. This catches things
1815 // like debug information.
1816 if (GV->getSection() == "llvm.metadata")
1817 return NotPrinted;
1818
1819 return NotSpecial;
1820}
1821
Anton Korobeynikove641b522009-08-05 09:29:56 +00001822// PrintEscapedString - Print each character of the specified string, escaping
1823// it if it is not printable or if it is an escape char.
1824static void PrintEscapedString(const char *Str, unsigned Length,
1825 raw_ostream &Out) {
1826 for (unsigned i = 0; i != Length; ++i) {
1827 unsigned char C = Str[i];
1828 if (isprint(C) && C != '\\' && C != '"')
1829 Out << C;
1830 else if (C == '\\')
1831 Out << "\\\\";
1832 else if (C == '\"')
1833 Out << "\\\"";
1834 else if (C == '\t')
1835 Out << "\\t";
1836 else
1837 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1838 }
1839}
1840
1841// PrintEscapedString - Print each character of the specified string, escaping
1842// it if it is not printable or if it is an escape char.
1843static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1844 PrintEscapedString(Str.c_str(), Str.size(), Out);
1845}
Chris Lattner9a571ba2006-03-07 22:58:23 +00001846
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001847bool CWriter::doInitialization(Module &M) {
Daniel Dunbar53448652009-07-17 03:43:21 +00001848 FunctionPass::doInitialization(M);
1849
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001850 // Initialize
1851 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001852
Reid Spencer519e2392007-01-29 17:51:02 +00001853 TD = new TargetData(&M);
1854 IL = new IntrinsicLowering(*TD);
1855 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001856
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001857 // Ensure that all structure types have names...
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001858 Mang = new Mangler(M);
Chris Lattnerba9c6432005-11-10 21:39:29 +00001859 Mang->markCharUnacceptable('.');
Chris Lattnerc59c1182003-11-16 22:06:14 +00001860
Chris Lattner9a571ba2006-03-07 22:58:23 +00001861 // Keep track of which functions are static ctors/dtors so they can have
1862 // an attribute added to their prototypes.
1863 std::set<Function*> StaticCtors, StaticDtors;
1864 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1865 I != E; ++I) {
1866 switch (getGlobalVariableClass(I)) {
1867 default: break;
1868 case GlobalCtors:
1869 FindStaticTors(I, StaticCtors);
1870 break;
1871 case GlobalDtors:
1872 FindStaticTors(I, StaticDtors);
1873 break;
1874 }
1875 }
1876
Chris Lattner16c7bb22002-05-09 02:28:59 +00001877 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001878 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001879 Out << "#include <stdarg.h>\n"; // Varargs support
1880 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman271515a2008-04-02 23:52:49 +00001881 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001882
Chris Lattnercf135cb2003-06-02 03:10:53 +00001883 // Provide a definition for `bool' if not compiling with a C++ compiler.
1884 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001885 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001886
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001887 << "\n\n/* Support for floating point constants */\n"
1888 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001889 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001890 << "typedef struct { unsigned long long f1; unsigned short f2; "
1891 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001892 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001893 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1894 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001895 << "\n\n/* Global Declarations */\n";
1896
1897 // First output all the declarations for the program, because C requires
1898 // Functions & globals to be declared before they are used.
1899 //
Anton Korobeynikove641b522009-08-05 09:29:56 +00001900 if (!M.getModuleInlineAsm().empty()) {
1901 Out << "/* Module asm statements */\n"
1902 << "asm(";
1903
1904 // Split the string into lines, to make it easier to read the .ll file.
1905 std::string Asm = M.getModuleInlineAsm();
1906 size_t CurPos = 0;
1907 size_t NewLine = Asm.find_first_of('\n', CurPos);
1908 while (NewLine != std::string::npos) {
1909 // We found a newline, print the portion of the asm string from the
1910 // last newline up to this newline.
1911 Out << "\"";
1912 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1913 Out);
1914 Out << "\\n\"\n";
1915 CurPos = NewLine+1;
1916 NewLine = Asm.find_first_of('\n', CurPos);
1917 }
1918 Out << "\"";
1919 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1920 Out << "\");\n"
1921 << "/* End Module asm statements */\n";
1922 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001923
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001924 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001925 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001926
Chris Lattnera4d4a852002-08-19 21:48:40 +00001927 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001928 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001929 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001930 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1931 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001932
Dale Johannesenaafce772008-05-14 20:12:51 +00001933 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1934 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001935 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001936 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001937 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001938 else
1939 continue; // Internal Global
1940
1941 // Thread Local Storage
1942 if (I->isThreadLocal())
1943 Out << "__thread ";
1944
1945 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1946
1947 if (I->hasExternalWeakLinkage())
1948 Out << " __EXTERNAL_WEAK__";
1949 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001950 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001951 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001952
Chris Lattnera4d4a852002-08-19 21:48:40 +00001953 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001954 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001955 Out << "double fmod(double, double);\n"; // Support for FP rem
1956 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001957 Out << "long double fmodl(long double, long double);\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001958
Chris Lattner9a571ba2006-03-07 22:58:23 +00001959 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1960 // Don't print declarations for intrinsic functions.
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001961 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Reid Spencer2cb46e12006-10-22 09:58:21 +00001962 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001963 if (I->hasExternalWeakLinkage())
1964 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001965 printFunctionSignature(I, true);
Evan Cheng3e3aa862008-06-07 07:50:29 +00001966 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001967 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001968 if (I->hasExternalWeakLinkage())
1969 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00001970 if (StaticCtors.count(I))
1971 Out << " __ATTRIBUTE_CTOR__";
1972 if (StaticDtors.count(I))
1973 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001974 if (I->hasHiddenVisibility())
1975 Out << " __HIDDEN__";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001976
1977 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar8f603022009-07-22 21:10:12 +00001978 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001979
Chris Lattner9a571ba2006-03-07 22:58:23 +00001980 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00001981 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00001982 }
1983
Joel Stanley54f60322003-06-25 04:52:09 +00001984 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00001985 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00001986 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001987 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1988 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00001989 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001990 // Ignore special globals, such as debug info.
1991 if (getGlobalVariableClass(I))
1992 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001993
Rafael Espindolabb46f522009-01-15 20:18:42 +00001994 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00001995 Out << "static ";
1996 else
1997 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001998
1999 // Thread Local Storage
2000 if (I->isThreadLocal())
2001 Out << "__thread ";
2002
Reid Spencer251f2142007-01-09 17:09:09 +00002003 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002004 GetValueName(I));
Chris Lattner2580d4f2003-11-03 17:32:38 +00002005
2006 if (I->hasLinkOnceLinkage())
2007 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00002008 else if (I->hasCommonLinkage()) // FIXME is this right?
2009 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00002010 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002011 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00002012 else if (I->hasExternalWeakLinkage())
2013 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002014 if (I->hasHiddenVisibility())
2015 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00002016 Out << ";\n";
2017 }
2018 }
2019
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002020 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002021 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002022 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002023 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00002024 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002025 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002026 // Ignore special globals, such as debug info.
2027 if (getGlobalVariableClass(I))
2028 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002029
Rafael Espindolabb46f522009-01-15 20:18:42 +00002030 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00002031 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002032 else if (I->hasDLLImportLinkage())
2033 Out << "__declspec(dllimport) ";
2034 else if (I->hasDLLExportLinkage())
2035 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002036
2037 // Thread Local Storage
2038 if (I->isThreadLocal())
2039 Out << "__thread ";
2040
Reid Spencer251f2142007-01-09 17:09:09 +00002041 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002042 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00002043 if (I->hasLinkOnceLinkage())
2044 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00002045 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002046 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00002047 else if (I->hasCommonLinkage())
2048 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00002049
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002050 if (I->hasHiddenVisibility())
2051 Out << " __HIDDEN__";
2052
Chris Lattner5ea326a2003-11-03 17:35:00 +00002053 // If the initializer is not null, emit the initializer. If it is null,
2054 // we try to avoid emitting large amounts of zeros. The problem with
2055 // this, however, occurs when the variable has weak linkage. In this
2056 // case, the assembler will complain about the variable being both weak
2057 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00002058 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002059 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00002060 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00002061 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002062 } else if (I->hasWeakLinkage()) {
2063 // We have to specify an initializer, but it doesn't have to be
2064 // complete. If the value is an aggregate, print out { 0 }, and let
2065 // the compiler figure out the rest of the zeros.
2066 Out << " = " ;
2067 if (isa<StructType>(I->getInitializer()->getType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00002068 isa<VectorType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002069 Out << "{ 0 }";
Dan Gohman193c2352008-06-02 21:30:49 +00002070 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2071 // As with structs and vectors, but with an extra set of braces
2072 // because arrays are wrapped in structs.
2073 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002074 } else {
2075 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00002076 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002077 }
Chris Lattner940b08d2003-06-06 07:10:24 +00002078 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00002079 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00002080 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002081 }
2082
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002083 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00002084 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002085
2086 // Emit some helper functions for dealing with FCMP instruction's
2087 // predicates
2088 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2089 Out << "return X == X && Y == Y; }\n";
2090 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2091 Out << "return X != X || Y != Y; }\n";
2092 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002093 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002094 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002095 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002096 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002097 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002098 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002099 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002100 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002101 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002102 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002103 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002104 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002105 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002106 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002107 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002108 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002109 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002110 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002111 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002112 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002113 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002114 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002115 Out << "return X >= Y ; }\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002116 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002117}
2118
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002119
Chris Lattner9860e772003-10-12 04:36:29 +00002120/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00002121void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00002122 // Scan the module for floating point constants. If any FP constant is used
2123 // in the function, we want to redirect it here so that we do not depend on
2124 // the precision of the printed form, unless the printed form preserves
2125 // precision.
2126 //
Chris Lattner68758072004-05-09 06:20:51 +00002127 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2128 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002129 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002130
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002131 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002132}
Chris Lattner9860e772003-10-12 04:36:29 +00002133
Chris Lattneraecc22a2008-10-22 04:53:16 +00002134void CWriter::printFloatingPointConstants(const Constant *C) {
2135 // If this is a constant expression, recursively check for constant fp values.
2136 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2137 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2138 printFloatingPointConstants(CE->getOperand(i));
2139 return;
2140 }
2141
2142 // Otherwise, check for a FP constant that we need to print.
2143 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2144 if (FPC == 0 ||
2145 // Do not put in FPConstantMap if safe.
2146 isFPCSafeToPrint(FPC) ||
2147 // Already printed this constant?
2148 FPConstantMap.count(FPC))
2149 return;
2150
2151 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2152
Owen Anderson1d0be152009-08-13 21:58:54 +00002153 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002154 double Val = FPC->getValueAPF().convertToDouble();
2155 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2156 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2157 << " = 0x" << utohexstr(i)
2158 << "ULL; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002159 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002160 float Val = FPC->getValueAPF().convertToFloat();
2161 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2162 getZExtValue();
2163 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2164 << " = 0x" << utohexstr(i)
2165 << "U; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002166 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002167 // api needed to prevent premature destruction
2168 APInt api = FPC->getValueAPF().bitcastToAPInt();
2169 const uint64_t *p = api.getRawData();
2170 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002171 << " = { 0x" << utohexstr(p[0])
2172 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002173 << "}; /* Long double constant */\n";
Anton Korobeynikovefc3f3a2009-08-26 17:39:23 +00002174 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2175 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002176 APInt api = FPC->getValueAPF().bitcastToAPInt();
2177 const uint64_t *p = api.getRawData();
2178 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2179 << " = { 0x"
2180 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2181 << "}; /* Long double constant */\n";
2182
2183 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002184 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002185 }
2186}
2187
2188
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002189
Chris Lattner2db41cd2002-09-20 15:12:13 +00002190/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002191/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002192///
Reid Spencer78d033e2007-01-06 07:24:44 +00002193void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002194 Out << "/* Helper union for bitcasts */\n";
2195 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002196 Out << " unsigned int Int32;\n";
2197 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002198 Out << " float Float;\n";
2199 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002200 Out << "} llvmBitCastUnion;\n";
2201
Chris Lattnerb15fde22005-03-06 02:28:23 +00002202 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002203 TypeSymbolTable::const_iterator I = TST.begin();
2204 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002205
2206 // If there are no type names, exit early.
2207 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002208
Chris Lattner58d04d42002-09-20 15:18:30 +00002209 // Print out forward declarations for structure types before anything else!
2210 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002211 for (; I != End; ++I) {
2212 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
2213 Out << Name << ";\n";
2214 TypeNames.insert(std::make_pair(I->second, Name));
2215 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002216
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002217 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002218
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002219 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002220 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002221 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002222 for (I = TST.begin(); I != End; ++I) {
Chris Lattner36c975c2005-11-10 18:53:25 +00002223 std::string Name = "l_" + Mang->makeNameProper(I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002224 Out << "typedef ";
Chris Lattnera80cc932007-01-16 18:02:45 +00002225 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002226 Out << ";\n";
2227 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002228
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002229 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002230
Chris Lattner2c601a72002-09-20 15:05:40 +00002231 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002232 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002233
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002234 // Loop over all structures then push them into the stack so they are
2235 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002236 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002237 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002238 for (I = TST.begin(); I != End; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +00002239 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002240 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002241 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002242}
2243
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002244// Push the struct onto the stack and recursively push all structs
2245// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002246//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002247// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002248//
Chris Lattner2c601a72002-09-20 15:05:40 +00002249void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002250 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002251 // Don't walk through pointers.
Chris Lattner42a75512007-01-15 02:27:26 +00002252 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002253
2254 // Print all contained types first.
2255 for (Type::subtype_iterator I = Ty->subtype_begin(),
2256 E = Ty->subtype_end(); I != E; ++I)
2257 printContainedStructs(*I, StructPrinted);
2258
Dan Gohman193c2352008-06-02 21:30:49 +00002259 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002260 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002261 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002262 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002263 std::string Name = TypeNames[Ty];
2264 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002265 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002266 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002267 }
2268}
2269
Chris Lattner4cda8352002-08-20 16:55:48 +00002270void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002271 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002272 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002273
Rafael Espindolabb46f522009-01-15 20:18:42 +00002274 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002275 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2276 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002277 switch (F->getCallingConv()) {
2278 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002279 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002280 break;
2281 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002282 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002283 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002284 default:
2285 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002286 }
2287
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002288 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002289 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002290 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002291
2292 std::stringstream FunctionInnards;
2293
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002294 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002295 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002296
Chris Lattner0c54d892006-05-23 23:39:48 +00002297 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002298 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002299 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002300 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002301 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002302
2303 // If this is a struct-return function, don't print the hidden
2304 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002305 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002306 assert(I != E && "Invalid struct return function!");
2307 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002308 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002309 }
2310
Chris Lattneredd8ce12003-05-03 03:14:35 +00002311 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002312 for (; I != E; ++I) {
2313 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002314 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002315 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002316 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002317 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002318 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002319 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002320 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002321 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002322 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002323 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002324 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002325 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002326 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002327 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002328 }
2329 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002330 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002331 // Loop over the arguments, printing them.
2332 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002333 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002334
2335 // If this is a struct-return function, don't print the hidden
2336 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002337 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002338 assert(I != E && "Invalid struct return function!");
2339 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002340 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002341 }
2342
2343 for (; I != E; ++I) {
2344 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002345 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002346 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng3d794782008-01-11 23:10:11 +00002347 assert(isa<PointerType>(ArgTy));
2348 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2349 }
2350 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002351 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002352 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002353 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002354 }
2355 }
2356
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002357 // Finish printing arguments... if this is a vararg function, print the ...,
2358 // unless there are no known types, in which case, we just emit ().
2359 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002360 if (FT->isVarArg() && PrintedArg) {
2361 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002362 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002363 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002364 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002365 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002366 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002367
2368 // Get the return tpe for the function.
2369 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002370 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002371 RetTy = F->getReturnType();
2372 else {
2373 // If this is a struct-return function, print the struct-return type.
2374 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2375 }
2376
2377 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002378 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002379 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002380 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002381}
2382
Reid Spencer22586642006-12-17 20:24:50 +00002383static inline bool isFPIntBitCast(const Instruction &I) {
2384 if (!isa<BitCastInst>(I))
2385 return false;
2386 const Type *SrcTy = I.getOperand(0)->getType();
2387 const Type *DstTy = I.getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002388 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2389 (DstTy->isFloatingPoint() && SrcTy->isInteger());
Reid Spencer22586642006-12-17 20:24:50 +00002390}
2391
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002392void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002393 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002394 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002395
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002396 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002397 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002398
2399 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002400 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002401 const Type *StructTy =
2402 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2403 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002404 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002405 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002406
Chris Lattner0c54d892006-05-23 23:39:48 +00002407 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002408 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002409 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002410 Out << " = &StructReturn;\n";
2411 }
2412
2413 bool PrintedVar = false;
2414
Chris Lattner497e19a2002-05-09 20:39:03 +00002415 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002416 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002417 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002418 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002419 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002420 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002421 PrintedVar = true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002422 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2423 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002424 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002425 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002426 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002427
Chris Lattner84e66652003-05-03 07:11:00 +00002428 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2429 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002430 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002431 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002432 Out << ";\n";
2433 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002434 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002435 }
2436 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002437 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002438 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002439 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002440 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002441 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002442 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002443 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002444 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002445
Chris Lattner0c54d892006-05-23 23:39:48 +00002446 if (PrintedVar)
2447 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002448
Chris Lattner395fd592004-12-13 21:52:52 +00002449 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002450 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002451
Chris Lattner16c7bb22002-05-09 02:28:59 +00002452 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002453 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002454 if (Loop *L = LI->getLoopFor(BB)) {
2455 if (L->getHeader() == BB && L->getParentLoop() == 0)
2456 printLoop(L);
2457 } else {
2458 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002459 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002460 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002461
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002462 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002463}
2464
Chris Lattnercb3ad012004-05-09 20:41:32 +00002465void CWriter::printLoop(Loop *L) {
2466 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2467 << "' to make GCC happy */\n";
2468 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2469 BasicBlock *BB = L->getBlocks()[i];
2470 Loop *BBLoop = LI->getLoopFor(BB);
2471 if (BBLoop == L)
2472 printBasicBlock(BB);
2473 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002474 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002475 }
2476 Out << " } while (1); /* end of syntactic loop '"
2477 << L->getHeader()->getName() << "' */\n";
2478}
2479
2480void CWriter::printBasicBlock(BasicBlock *BB) {
2481
2482 // Don't print the label for the basic block if there are no uses, or if
2483 // the only terminator use is the predecessor basic block's terminator.
2484 // We have to scan the use list because PHI nodes use basic blocks too but
2485 // do not require a label to be generated.
2486 //
2487 bool NeedsLabel = false;
2488 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2489 if (isGotoCodeNecessary(*PI, BB)) {
2490 NeedsLabel = true;
2491 break;
2492 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002493
Bill Wendling145aad02007-02-23 22:45:08 +00002494 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002495
Chris Lattnercb3ad012004-05-09 20:41:32 +00002496 // Output all of the instructions in the basic block...
2497 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2498 ++II) {
2499 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002500 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2501 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002502 outputLValue(II);
2503 else
2504 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002505 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002506 Out << ";\n";
2507 }
2508 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002509
Chris Lattnere56d9462008-05-31 09:23:55 +00002510 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002511 visit(*BB->getTerminator());
2512}
2513
2514
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002515// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002516// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002517//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002518void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002519 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002520 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002521
2522 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002523 Out << " return StructReturn;\n";
2524 return;
2525 }
2526
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002527 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002528 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002529 &*--I.getParent()->getParent()->end() == I.getParent() &&
2530 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002531 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002532 }
Chris Lattner44408262002-05-09 03:50:42 +00002533
Dan Gohman76612792008-04-23 21:49:29 +00002534 if (I.getNumOperands() > 1) {
2535 Out << " {\n";
2536 Out << " ";
2537 printType(Out, I.getParent()->getParent()->getReturnType());
2538 Out << " llvm_cbe_mrv_temp = {\n";
2539 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2540 Out << " ";
2541 writeOperand(I.getOperand(i));
2542 if (i != e - 1)
2543 Out << ",";
2544 Out << "\n";
2545 }
2546 Out << " };\n";
2547 Out << " return llvm_cbe_mrv_temp;\n";
2548 Out << " }\n";
2549 return;
2550 }
2551
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002552 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002553 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002554 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002555 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002556 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002557 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002558}
2559
Chris Lattnera9f5e052003-04-22 20:19:52 +00002560void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002561
Chris Lattnera9f5e052003-04-22 20:19:52 +00002562 Out << " switch (";
2563 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002564 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002565 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002566 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002567 Out << ";\n";
2568 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2569 Out << " case ";
2570 writeOperand(SI.getOperand(i));
2571 Out << ":\n";
2572 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002573 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002574 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerefd02c72005-03-19 17:35:11 +00002575 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002576 Out << " break;\n";
2577 }
2578 Out << " }\n";
2579}
2580
Chris Lattnera9d12c02004-10-16 18:12:13 +00002581void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002582 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002583}
2584
Chris Lattnercb3ad012004-05-09 20:41:32 +00002585bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2586 /// FIXME: This should be reenabled, but loop reordering safe!!
2587 return true;
2588
Chris Lattner67c2d182005-03-18 16:12:37 +00002589 if (next(Function::iterator(From)) != Function::iterator(To))
2590 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002591
2592 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002593
Chris Lattnercb3ad012004-05-09 20:41:32 +00002594 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002595 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002596 return false;
2597}
2598
John Criswell57bbfce2004-10-20 14:38:39 +00002599void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002600 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002601 unsigned Indent) {
2602 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2603 PHINode *PN = cast<PHINode>(I);
2604 // Now we have to do the printing.
2605 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2606 if (!isa<UndefValue>(IV)) {
2607 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002608 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002609 writeOperand(IV);
2610 Out << "; /* for PHI node */\n";
2611 }
2612 }
2613}
2614
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002615void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002616 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002617 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002618 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002619 writeOperand(Succ);
2620 Out << ";\n";
2621 }
2622}
2623
Misha Brukman37f92e22003-09-11 22:34:13 +00002624// Branch instruction printing - Avoid printing out a branch to a basic block
2625// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002626//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002627void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002628
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002629 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002630 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002631 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002632 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002633 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002634
John Criswell57bbfce2004-10-20 14:38:39 +00002635 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002636 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002637
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002638 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002639 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002640 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002641 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002642 }
2643 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002644 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002645 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002646 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002647 Out << ") {\n";
2648
John Criswell57bbfce2004-10-20 14:38:39 +00002649 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002650 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002651 }
2652
2653 Out << " }\n";
2654 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002655 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002656 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002657 }
2658 Out << "\n";
2659}
2660
Chris Lattner84e66652003-05-03 07:11:00 +00002661// PHI nodes get copied into temporary values at the end of predecessor basic
2662// blocks. We now need to copy these temporary values into the REAL value for
2663// the PHI.
2664void CWriter::visitPHINode(PHINode &I) {
2665 writeOperand(&I);
2666 Out << "__PHI_TEMPORARY";
2667}
2668
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002669
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002670void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002671 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002672 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002673
2674 // We must cast the results of binary operations which might be promoted.
2675 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002676 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2677 (I.getType() == Type::getInt16Ty(I.getContext()))
2678 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002679 needsCast = true;
2680 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002681 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002682 Out << ")(";
2683 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002684
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002685 // If this is a negation operation, print it out as such. For FP, we don't
2686 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002687 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002688 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002689 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002690 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002691 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002692 Out << "-(";
2693 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2694 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002695 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002696 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002697 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002698 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002699 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002700 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002701 else // all 3 flavors of long double
2702 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002703 writeOperand(I.getOperand(0));
2704 Out << ", ";
2705 writeOperand(I.getOperand(1));
2706 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002707 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002708
2709 // Write out the cast of the instruction's value back to the proper type
2710 // if necessary.
2711 bool NeedsClosingParens = writeInstructionCast(I);
2712
2713 // Certain instructions require the operand to be forced to a specific type
2714 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2715 // below for operand 1
2716 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002717
2718 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002719 case Instruction::Add:
2720 case Instruction::FAdd: Out << " + "; break;
2721 case Instruction::Sub:
2722 case Instruction::FSub: Out << " - "; break;
2723 case Instruction::Mul:
2724 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002725 case Instruction::URem:
2726 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002727 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002728 case Instruction::UDiv:
2729 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002730 case Instruction::FDiv: Out << " / "; break;
2731 case Instruction::And: Out << " & "; break;
2732 case Instruction::Or: Out << " | "; break;
2733 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002734 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002735 case Instruction::LShr:
2736 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002737 default:
2738#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002739 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002740#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002741 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002742 }
2743
Reid Spencer1628cec2006-10-26 06:15:43 +00002744 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2745 if (NeedsClosingParens)
2746 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002747 }
2748
Brian Gaeke031a1122003-06-23 20:00:51 +00002749 if (needsCast) {
2750 Out << "))";
2751 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002752}
2753
Reid Spencere4d87aa2006-12-23 06:05:41 +00002754void CWriter::visitICmpInst(ICmpInst &I) {
2755 // We must cast the results of icmp which might be promoted.
2756 bool needsCast = false;
2757
2758 // Write out the cast of the instruction's value back to the proper type
2759 // if necessary.
2760 bool NeedsClosingParens = writeInstructionCast(I);
2761
2762 // Certain icmp predicate require the operand to be forced to a specific type
2763 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2764 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002765 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002766
2767 switch (I.getPredicate()) {
2768 case ICmpInst::ICMP_EQ: Out << " == "; break;
2769 case ICmpInst::ICMP_NE: Out << " != "; break;
2770 case ICmpInst::ICMP_ULE:
2771 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2772 case ICmpInst::ICMP_UGE:
2773 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2774 case ICmpInst::ICMP_ULT:
2775 case ICmpInst::ICMP_SLT: Out << " < "; break;
2776 case ICmpInst::ICMP_UGT:
2777 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002778 default:
2779#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002780 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002781#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002782 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002783 }
2784
Chris Lattner5bda9e42007-09-15 06:51:03 +00002785 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002786 if (NeedsClosingParens)
2787 Out << "))";
2788
2789 if (needsCast) {
2790 Out << "))";
2791 }
2792}
2793
2794void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002795 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2796 Out << "0";
2797 return;
2798 }
2799 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2800 Out << "1";
2801 return;
2802 }
2803
2804 const char* op = 0;
2805 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002806 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002807 case FCmpInst::FCMP_ORD: op = "ord"; break;
2808 case FCmpInst::FCMP_UNO: op = "uno"; break;
2809 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2810 case FCmpInst::FCMP_UNE: op = "une"; break;
2811 case FCmpInst::FCMP_ULT: op = "ult"; break;
2812 case FCmpInst::FCMP_ULE: op = "ule"; break;
2813 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2814 case FCmpInst::FCMP_UGE: op = "uge"; break;
2815 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2816 case FCmpInst::FCMP_ONE: op = "one"; break;
2817 case FCmpInst::FCMP_OLT: op = "olt"; break;
2818 case FCmpInst::FCMP_OLE: op = "ole"; break;
2819 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2820 case FCmpInst::FCMP_OGE: op = "oge"; break;
2821 }
2822
2823 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002824 // Write the first operand
2825 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002826 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002827 // Write the second operand
2828 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002829 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002830}
2831
Reid Spencer555a0b12006-12-11 20:39:15 +00002832static const char * getFloatBitCastField(const Type *Ty) {
2833 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002834 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002835 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002836 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002837 case Type::IntegerTyID: {
2838 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2839 if (NumBits <= 32)
2840 return "Int32";
2841 else
2842 return "Int64";
2843 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002844 }
2845}
2846
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002847void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002848 const Type *DstTy = I.getType();
2849 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002850 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002851 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002852 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002853 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002854 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2855 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002856 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002857 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002858 Out << ')';
2859 return;
2860 }
2861
2862 Out << '(';
2863 printCast(I.getOpcode(), SrcTy, DstTy);
2864
2865 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002866 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2867 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002868 Out << "0-";
2869
2870 writeOperand(I.getOperand(0));
2871
Owen Anderson1d0be152009-08-13 21:58:54 +00002872 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002873 (I.getOpcode() == Instruction::Trunc ||
2874 I.getOpcode() == Instruction::FPToUI ||
2875 I.getOpcode() == Instruction::FPToSI ||
2876 I.getOpcode() == Instruction::PtrToInt)) {
2877 // Make sure we really get a trunc to bool by anding the operand with 1
2878 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002879 }
Chris Lattner72623362007-05-03 02:57:13 +00002880 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002881}
2882
Chris Lattner9f24a072004-03-12 05:52:14 +00002883void CWriter::visitSelectInst(SelectInst &I) {
2884 Out << "((";
2885 writeOperand(I.getCondition());
2886 Out << ") ? (";
2887 writeOperand(I.getTrueValue());
2888 Out << ") : (";
2889 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002890 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002891}
2892
2893
Chris Lattnerc2421432004-05-09 04:30:20 +00002894void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002895 // This is used to keep track of intrinsics that get generated to a lowered
2896 // function. We must generate the prototypes before the function body which
2897 // will only be expanded on first use (by the loop below).
2898 std::vector<Function*> prototypesToGen;
2899
2900 // Examine all the instructions in this function to find the intrinsics that
2901 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002902 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002903 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2904 if (CallInst *CI = dyn_cast<CallInst>(I++))
2905 if (Function *F = CI->getCalledFunction())
2906 switch (F->getIntrinsicID()) {
2907 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002908 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002909 case Intrinsic::vastart:
2910 case Intrinsic::vacopy:
2911 case Intrinsic::vaend:
2912 case Intrinsic::returnaddress:
2913 case Intrinsic::frameaddress:
2914 case Intrinsic::setjmp:
2915 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002916 case Intrinsic::prefetch:
Jim Laskey7075d6f2006-03-08 19:31:15 +00002917 case Intrinsic::dbg_stoppoint:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002918 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002919 case Intrinsic::x86_sse_cmp_ss:
2920 case Intrinsic::x86_sse_cmp_ps:
2921 case Intrinsic::x86_sse2_cmp_sd:
2922 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002923 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002924 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002925 break;
2926 default:
Chris Lattner87242152006-03-13 23:09:05 +00002927 // If this is an intrinsic that directly corresponds to a GCC
2928 // builtin, we handle it.
2929 const char *BuiltinName = "";
2930#define GET_GCC_BUILTIN_NAME
2931#include "llvm/Intrinsics.gen"
2932#undef GET_GCC_BUILTIN_NAME
2933 // If we handle it, don't lower it.
2934 if (BuiltinName[0]) break;
2935
Chris Lattnerc2421432004-05-09 04:30:20 +00002936 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002937 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002938 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002939 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002940
Reid Spencer519e2392007-01-29 17:51:02 +00002941 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002942 if (Before) { // Move iterator to instruction after call
2943 I = Before; ++I;
2944 } else {
2945 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002946 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002947 // If the intrinsic got lowered to another call, and that call has
2948 // a definition then we need to make sure its prototype is emitted
2949 // before any calls to it.
2950 if (CallInst *Call = dyn_cast<CallInst>(I))
2951 if (Function *NewF = Call->getCalledFunction())
2952 if (!NewF->isDeclaration())
2953 prototypesToGen.push_back(NewF);
2954
Chris Lattner87242152006-03-13 23:09:05 +00002955 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002956 }
Chris Lattner4ef51372004-02-14 00:31:10 +00002957
Reid Spencer69f80a62007-04-12 21:00:45 +00002958 // We may have collected some prototypes to emit in the loop above.
2959 // Emit them now, before the function that uses them is emitted. But,
2960 // be careful not to emit them twice.
2961 std::vector<Function*>::iterator I = prototypesToGen.begin();
2962 std::vector<Function*>::iterator E = prototypesToGen.end();
2963 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00002964 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002965 Out << '\n';
2966 printFunctionSignature(*I, true);
2967 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00002968 }
2969 }
2970}
Chris Lattner4ef51372004-02-14 00:31:10 +00002971
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002972void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00002973 if (isa<InlineAsm>(I.getOperand(0)))
2974 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00002975
Chris Lattner87242152006-03-13 23:09:05 +00002976 bool WroteCallee = false;
2977
Chris Lattner18ac3c82003-05-08 18:41:45 +00002978 // Handle intrinsic function calls first...
2979 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00002980 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2981 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002982 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00002983
Chris Lattner4394d512004-11-13 22:21:56 +00002984 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002985
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002986 const PointerType *PTy = cast<PointerType>(Callee->getType());
2987 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2988
Chris Lattner0c54d892006-05-23 23:39:48 +00002989 // If this is a call to a struct-return function, assign to the first
2990 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00002991 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00002992 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00002993 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002994 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00002995 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00002996 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00002997 }
2998
Chris Lattnerfe673d92005-05-06 06:53:07 +00002999 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003000
3001 if (!WroteCallee) {
3002 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00003003 // the pointer. Ditto for indirect calls with byval arguments.
3004 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00003005
Chris Lattner0c54d892006-05-23 23:39:48 +00003006 // GCC is a real PITA. It does not permit codegening casts of functions to
3007 // function pointers if they are in a call (it generates a trap instruction
3008 // instead!). We work around this by inserting a cast to void* in between
3009 // the function and the function pointer cast. Unfortunately, we can't just
3010 // form the constant expression here, because the folder will immediately
3011 // nuke it.
3012 //
3013 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3014 // that void* and function pointers have the same size. :( To deal with this
3015 // in the common case, we handle casts where the number of arguments passed
3016 // match exactly.
3017 //
3018 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00003019 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00003020 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3021 NeedsCast = true;
3022 Callee = RF;
3023 }
3024
3025 if (NeedsCast) {
3026 // Ok, just cast the pointer type.
3027 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00003028 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00003029 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00003030 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00003031 else if (hasByVal)
3032 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3033 else
3034 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00003035 Out << ")(void*)";
3036 }
3037 writeOperand(Callee);
3038 if (NeedsCast) Out << ')';
3039 }
3040
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003041 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003042
Chris Lattner4394d512004-11-13 22:21:56 +00003043 unsigned NumDeclaredParams = FTy->getNumParams();
3044
Chris Lattner0c54d892006-05-23 23:39:48 +00003045 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3046 unsigned ArgNo = 0;
3047 if (isStructRet) { // Skip struct return argument.
3048 ++AI;
3049 ++ArgNo;
3050 }
3051
3052 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00003053 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00003054 if (PrintedArg) Out << ", ";
3055 if (ArgNo < NumDeclaredParams &&
3056 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003057 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00003058 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003059 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003060 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003061 }
Evan Cheng3d794782008-01-11 23:10:11 +00003062 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003063 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003064 writeOperandDeref(*AI);
3065 else
3066 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003067 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003068 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003069 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003070}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003071
Chris Lattner2299fec2008-03-02 08:29:41 +00003072/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3073/// if the entire call is handled, return false it it wasn't handled, and
3074/// optionally set 'WroteCallee' if the callee has already been printed out.
3075bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3076 bool &WroteCallee) {
3077 switch (ID) {
3078 default: {
3079 // If this is an intrinsic that directly corresponds to a GCC
3080 // builtin, we emit it here.
3081 const char *BuiltinName = "";
3082 Function *F = I.getCalledFunction();
3083#define GET_GCC_BUILTIN_NAME
3084#include "llvm/Intrinsics.gen"
3085#undef GET_GCC_BUILTIN_NAME
3086 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3087
3088 Out << BuiltinName;
3089 WroteCallee = true;
3090 return false;
3091 }
3092 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003093 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003094 return true;
3095 case Intrinsic::vastart:
3096 Out << "0; ";
3097
3098 Out << "va_start(*(va_list*)";
3099 writeOperand(I.getOperand(1));
3100 Out << ", ";
3101 // Output the last argument to the enclosing function.
3102 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00003103 std::string msg;
3104 raw_string_ostream Msg(msg);
3105 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00003106 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00003107 << I.getParent()->getParent()->getName() << "'!";
3108 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00003109 }
3110 writeOperand(--I.getParent()->getParent()->arg_end());
3111 Out << ')';
3112 return true;
3113 case Intrinsic::vaend:
3114 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3115 Out << "0; va_end(*(va_list*)";
3116 writeOperand(I.getOperand(1));
3117 Out << ')';
3118 } else {
3119 Out << "va_end(*(va_list*)0)";
3120 }
3121 return true;
3122 case Intrinsic::vacopy:
3123 Out << "0; ";
3124 Out << "va_copy(*(va_list*)";
3125 writeOperand(I.getOperand(1));
3126 Out << ", *(va_list*)";
3127 writeOperand(I.getOperand(2));
3128 Out << ')';
3129 return true;
3130 case Intrinsic::returnaddress:
3131 Out << "__builtin_return_address(";
3132 writeOperand(I.getOperand(1));
3133 Out << ')';
3134 return true;
3135 case Intrinsic::frameaddress:
3136 Out << "__builtin_frame_address(";
3137 writeOperand(I.getOperand(1));
3138 Out << ')';
3139 return true;
3140 case Intrinsic::powi:
3141 Out << "__builtin_powi(";
3142 writeOperand(I.getOperand(1));
3143 Out << ", ";
3144 writeOperand(I.getOperand(2));
3145 Out << ')';
3146 return true;
3147 case Intrinsic::setjmp:
3148 Out << "setjmp(*(jmp_buf*)";
3149 writeOperand(I.getOperand(1));
3150 Out << ')';
3151 return true;
3152 case Intrinsic::longjmp:
3153 Out << "longjmp(*(jmp_buf*)";
3154 writeOperand(I.getOperand(1));
3155 Out << ", ";
3156 writeOperand(I.getOperand(2));
3157 Out << ')';
3158 return true;
3159 case Intrinsic::prefetch:
3160 Out << "LLVM_PREFETCH((const void *)";
3161 writeOperand(I.getOperand(1));
3162 Out << ", ";
3163 writeOperand(I.getOperand(2));
3164 Out << ", ";
3165 writeOperand(I.getOperand(3));
3166 Out << ")";
3167 return true;
3168 case Intrinsic::stacksave:
3169 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3170 // to work around GCC bugs (see PR1809).
3171 Out << "0; *((void**)&" << GetValueName(&I)
3172 << ") = __builtin_stack_save()";
3173 return true;
3174 case Intrinsic::dbg_stoppoint: {
3175 // If we use writeOperand directly we get a "u" suffix which is rejected
3176 // by gcc.
3177 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Anton Korobeynikov0802a1e2009-08-05 09:31:40 +00003178 std::string dir;
3179 GetConstantStringInfo(SPI.getDirectory(), dir);
3180 std::string file;
3181 GetConstantStringInfo(SPI.getFileName(), file);
Chris Lattner2299fec2008-03-02 08:29:41 +00003182 Out << "\n#line "
3183 << SPI.getLine()
Anton Korobeynikov0802a1e2009-08-05 09:31:40 +00003184 << " \""
3185 << dir << '/' << file << "\"\n";
Chris Lattner2299fec2008-03-02 08:29:41 +00003186 return true;
3187 }
Chris Lattner4e220122008-03-02 08:47:13 +00003188 case Intrinsic::x86_sse_cmp_ss:
3189 case Intrinsic::x86_sse_cmp_ps:
3190 case Intrinsic::x86_sse2_cmp_sd:
3191 case Intrinsic::x86_sse2_cmp_pd:
3192 Out << '(';
3193 printType(Out, I.getType());
3194 Out << ')';
3195 // Multiple GCC builtins multiplex onto this intrinsic.
3196 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003197 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003198 case 0: Out << "__builtin_ia32_cmpeq"; break;
3199 case 1: Out << "__builtin_ia32_cmplt"; break;
3200 case 2: Out << "__builtin_ia32_cmple"; break;
3201 case 3: Out << "__builtin_ia32_cmpunord"; break;
3202 case 4: Out << "__builtin_ia32_cmpneq"; break;
3203 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3204 case 6: Out << "__builtin_ia32_cmpnle"; break;
3205 case 7: Out << "__builtin_ia32_cmpord"; break;
3206 }
3207 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3208 Out << 'p';
3209 else
3210 Out << 's';
3211 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3212 Out << 's';
3213 else
3214 Out << 'd';
3215
3216 Out << "(";
3217 writeOperand(I.getOperand(1));
3218 Out << ", ";
3219 writeOperand(I.getOperand(2));
3220 Out << ")";
3221 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003222 case Intrinsic::ppc_altivec_lvsl:
3223 Out << '(';
3224 printType(Out, I.getType());
3225 Out << ')';
3226 Out << "__builtin_altivec_lvsl(0, (void*)";
3227 writeOperand(I.getOperand(1));
3228 Out << ")";
3229 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003230 }
3231}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003232
3233//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003234//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003235// of the per target tables
3236// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003237std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003238
3239 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3240
Dan Gohmancfbb2f02008-03-25 21:45:14 +00003241 const char *const *table = 0;
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003242
Chris Lattneraf76e592009-08-22 20:48:53 +00003243 // Grab the translation table from MCAsmInfo if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003244 if (!TAsm) {
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +00003245 std::string Triple = TheModule->getTargetTriple();
3246 if (Triple.empty())
3247 Triple = llvm::sys::getHostTriple();
3248
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003249 std::string E;
Chris Lattnerbfbc1de2009-08-12 16:41:44 +00003250 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3251 TAsm = Match->createAsmInfo(Triple);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003252 }
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003253 if (TAsm)
3254 table = TAsm->getAsmCBE();
3255
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003256 // Search the translation table if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003257 for (int i = 0; table && table[i]; i += 2)
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003258 if (c.Codes[0] == table[i])
3259 return table[i+1];
3260
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003261 // Default is identity.
Andrew Lenharth85f22282006-11-28 22:25:32 +00003262 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003263}
3264
3265//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003266static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003267 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3268 if (asmstr[i] == '\n')
3269 asmstr.replace(i, 1, "\\n");
3270 else if (asmstr[i] == '\t')
3271 asmstr.replace(i, 1, "\\t");
3272 else if (asmstr[i] == '$') {
3273 if (asmstr[i + 1] == '{') {
3274 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3275 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3276 std::string n = "%" +
3277 asmstr.substr(a + 1, b - a - 1) +
3278 asmstr.substr(i + 2, a - i - 2);
3279 asmstr.replace(i, b - i + 1, n);
3280 i += n.size() - 1;
3281 } else
3282 asmstr.replace(i, 1, "%");
3283 }
3284 else if (asmstr[i] == '%')//grr
3285 { asmstr.replace(i, 1, "%%"); ++i;}
3286
3287 return asmstr;
3288}
3289
Andrew Lenharth238581f2006-11-28 19:56:02 +00003290//TODO: assumptions about what consume arguments from the call are likely wrong
3291// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003292void CWriter::visitInlineAsm(CallInst &CI) {
3293 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003294 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003295
3296 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00003297 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003298 ;
3299 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3300 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3301 ResultVals.push_back(std::make_pair(&CI, (int)i));
3302 } else {
3303 ResultVals.push_back(std::make_pair(&CI, -1));
3304 }
3305
Chris Lattner67f631d2008-06-04 18:03:28 +00003306 // Fix up the asm string for gcc and emit it.
3307 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3308 Out << " :";
3309
3310 unsigned ValueCount = 0;
3311 bool IsFirst = true;
3312
3313 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003314 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003315 E = Constraints.end(); I != E; ++I) {
3316
3317 if (I->Type != InlineAsm::isOutput) {
3318 ++ValueCount;
3319 continue; // Ignore non-output constraints.
3320 }
3321
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003322 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003323 std::string C = InterpretASMConstraint(*I);
3324 if (C.empty()) continue;
3325
Chris Lattner67f631d2008-06-04 18:03:28 +00003326 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003327 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003328 IsFirst = false;
3329 }
3330
3331 // Unpack the dest.
3332 Value *DestVal;
3333 int DestValNo = -1;
3334
3335 if (ValueCount < ResultVals.size()) {
3336 DestVal = ResultVals[ValueCount].first;
3337 DestValNo = ResultVals[ValueCount].second;
3338 } else
3339 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3340
3341 if (I->isEarlyClobber)
3342 C = "&"+C;
3343
3344 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3345 if (DestValNo != -1)
3346 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003347 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003348 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003349 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003350
3351
3352 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003353 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003354 IsFirst = true;
3355 ValueCount = 0;
3356 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3357 E = Constraints.end(); I != E; ++I) {
3358 if (I->Type != InlineAsm::isInput) {
3359 ++ValueCount;
3360 continue; // Ignore non-input constraints.
3361 }
3362
3363 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3364 std::string C = InterpretASMConstraint(*I);
3365 if (C.empty()) continue;
3366
3367 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003368 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003369 IsFirst = false;
3370 }
3371
3372 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3373 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3374
3375 Out << "\"" << C << "\"(";
3376 if (!I->isIndirect)
3377 writeOperand(SrcVal);
3378 else
3379 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003380 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003381 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003382
3383 // Convert over the clobber constraints.
3384 IsFirst = true;
3385 ValueCount = 0;
3386 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3387 E = Constraints.end(); I != E; ++I) {
3388 if (I->Type != InlineAsm::isClobber)
3389 continue; // Ignore non-input constraints.
3390
3391 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3392 std::string C = InterpretASMConstraint(*I);
3393 if (C.empty()) continue;
3394
3395 if (!IsFirst) {
3396 Out << ", ";
3397 IsFirst = false;
3398 }
3399
3400 Out << '\"' << C << '"';
3401 }
3402
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003403 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003404}
3405
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003406void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003407 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003408 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003409 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003410 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003411 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003412 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003413 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003414 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003415 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003416 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003417}
3418
Chris Lattnere05252b42008-03-02 08:07:24 +00003419void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003420 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003421
3422 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003423 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003424 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003425 return;
3426 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003427
3428 // Find out if the last index is into a vector. If so, we have to print this
3429 // specially. Since vectors can't have elements of indexable type, only the
3430 // last index could possibly be of a vector element.
3431 const VectorType *LastIndexIsVector = 0;
3432 {
3433 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3434 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003435 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003436
3437 Out << "(";
3438
3439 // If the last index is into a vector, we can't print it as &a[i][j] because
3440 // we can't index into a vector with j in GCC. Instead, emit this as
3441 // (((float*)&a[i])+j)
3442 if (LastIndexIsVector) {
3443 Out << "((";
3444 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3445 Out << ")(";
3446 }
3447
3448 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003449
Chris Lattnere05252b42008-03-02 08:07:24 +00003450 // If the first index is 0 (very typical) we can do a number of
3451 // simplifications to clean up the code.
3452 Value *FirstOp = I.getOperand();
3453 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3454 // First index isn't simple, print it the hard way.
3455 writeOperand(Ptr);
3456 } else {
3457 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003458
Chris Lattnere05252b42008-03-02 08:07:24 +00003459 // Okay, emit the first operand. If Ptr is something that is already address
3460 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3461 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003462 writeOperandInternal(Ptr, Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00003463 } else if (I != E && isa<StructType>(*I)) {
3464 // If we didn't already emit the first operand, see if we can print it as
3465 // P->f instead of "P[0].f"
3466 writeOperand(Ptr);
3467 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3468 ++I; // eat the struct index as well.
3469 } else {
3470 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3471 Out << "(*";
3472 writeOperand(Ptr);
3473 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003474 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003475 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003476
Chris Lattnere05252b42008-03-02 08:07:24 +00003477 for (; I != E; ++I) {
Chris Lattner23e90702003-11-25 20:49:55 +00003478 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003479 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman193c2352008-06-02 21:30:49 +00003480 } else if (isa<ArrayType>(*I)) {
3481 Out << ".array[";
3482 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3483 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003484 } else if (!isa<VectorType>(*I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003485 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003486 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003487 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003488 } else {
3489 // If the last index is into a vector, then print it out as "+j)". This
3490 // works with the 'LastIndexIsVector' code above.
3491 if (isa<Constant>(I.getOperand()) &&
3492 cast<Constant>(I.getOperand())->isNullValue()) {
3493 Out << "))"; // avoid "+0".
3494 } else {
3495 Out << ")+(";
3496 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3497 Out << "))";
3498 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003499 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003500 }
3501 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003502}
3503
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003504void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3505 bool IsVolatile, unsigned Alignment) {
3506
3507 bool IsUnaligned = Alignment &&
3508 Alignment < TD->getABITypeAlignment(OperandType);
3509
3510 if (!IsUnaligned)
3511 Out << '*';
3512 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003513 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003514 if (IsUnaligned)
3515 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3516 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3517 if (IsUnaligned) {
3518 Out << "; } ";
3519 if (IsVolatile) Out << "volatile ";
3520 Out << "*";
3521 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003522 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003523 }
3524
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003525 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003526
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003527 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003528 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003529 if (IsUnaligned)
3530 Out << "->data";
3531 }
3532}
3533
3534void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003535 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3536 I.getAlignment());
3537
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003538}
3539
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003540void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003541 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3542 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003543 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003544 Value *Operand = I.getOperand(0);
3545 Constant *BitMask = 0;
3546 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3547 if (!ITy->isPowerOf2ByteWidth())
3548 // We have a bit width that doesn't match an even power-of-2 byte
3549 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneed707b2009-07-24 23:12:02 +00003550 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003551 if (BitMask)
3552 Out << "((";
3553 writeOperand(Operand);
3554 if (BitMask) {
3555 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003556 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003557 Out << ")";
3558 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003559}
3560
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003561void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003562 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003563 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003564}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003565
Chris Lattner4d45bd02003-10-18 05:57:43 +00003566void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003567 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003568 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003569 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003570 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003571 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003572}
3573
Chris Lattner33a44d92008-03-02 03:52:39 +00003574void CWriter::visitInsertElementInst(InsertElementInst &I) {
3575 const Type *EltTy = I.getType()->getElementType();
3576 writeOperand(I.getOperand(0));
3577 Out << ";\n ";
3578 Out << "((";
3579 printType(Out, PointerType::getUnqual(EltTy));
3580 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003581 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003582 Out << "] = (";
3583 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003584 Out << ")";
3585}
3586
Chris Lattner0452ed62008-03-02 03:57:08 +00003587void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3588 // We know that our operand is not inlined.
3589 Out << "((";
3590 const Type *EltTy =
3591 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3592 printType(Out, PointerType::getUnqual(EltTy));
3593 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3594 writeOperand(I.getOperand(1));
3595 Out << "]";
3596}
3597
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003598void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3599 Out << "(";
3600 printType(Out, SVI.getType());
3601 Out << "){ ";
3602 const VectorType *VT = SVI.getType();
3603 unsigned NumElts = VT->getNumElements();
3604 const Type *EltTy = VT->getElementType();
3605
3606 for (unsigned i = 0; i != NumElts; ++i) {
3607 if (i) Out << ", ";
3608 int SrcVal = SVI.getMaskValue(i);
3609 if ((unsigned)SrcVal >= NumElts*2) {
3610 Out << " 0/*undef*/ ";
3611 } else {
3612 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3613 if (isa<Instruction>(Op)) {
3614 // Do an extractelement of this value from the appropriate input.
3615 Out << "((";
3616 printType(Out, PointerType::getUnqual(EltTy));
3617 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003618 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003619 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3620 Out << "0";
3621 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003622 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003623 (NumElts-1)),
3624 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003625 }
3626 }
3627 }
3628 Out << "}";
3629}
Chris Lattner0452ed62008-03-02 03:57:08 +00003630
Dan Gohman193c2352008-06-02 21:30:49 +00003631void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3632 // Start by copying the entire aggregate value into the result variable.
3633 writeOperand(IVI.getOperand(0));
3634 Out << ";\n ";
3635
3636 // Then do the insert to update the field.
3637 Out << GetValueName(&IVI);
3638 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3639 i != e; ++i) {
3640 const Type *IndexedTy =
3641 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3642 if (isa<ArrayType>(IndexedTy))
3643 Out << ".array[" << *i << "]";
3644 else
3645 Out << ".field" << *i;
3646 }
3647 Out << " = ";
3648 writeOperand(IVI.getOperand(1));
3649}
3650
3651void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3652 Out << "(";
3653 if (isa<UndefValue>(EVI.getOperand(0))) {
3654 Out << "(";
3655 printType(Out, EVI.getType());
3656 Out << ") 0/*UNDEF*/";
3657 } else {
3658 Out << GetValueName(EVI.getOperand(0));
3659 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3660 i != e; ++i) {
3661 const Type *IndexedTy =
3662 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3663 if (isa<ArrayType>(IndexedTy))
3664 Out << ".array[" << *i << "]";
3665 else
3666 Out << ".field" << *i;
3667 }
3668 }
3669 Out << ")";
3670}
3671
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003672//===----------------------------------------------------------------------===//
3673// External Interface declaration
3674//===----------------------------------------------------------------------===//
3675
Chris Lattner1911fd42006-09-04 04:14:57 +00003676bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003677 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003678 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003679 CodeGenOpt::Level OptLevel) {
Chris Lattner0431c962005-06-25 02:48:37 +00003680 if (FileType != TargetMachine::AssemblyFile) return true;
3681
Gordon Henriksence224772008-01-07 01:30:38 +00003682 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003683 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003684 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003685 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003686 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003687 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003688 return false;
3689}