blob: c1c1d808e9a9c77197f74310086bd27d389b77fb [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"
Chris Lattner48130352010-01-13 06:38:18 +000028#include "llvm/ADT/SmallString.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000030#include "llvm/Analysis/ConstantsScanner.h"
Chris Lattnercb3ad012004-05-09 20:41:32 +000031#include "llvm/Analysis/FindUsedTypes.h"
32#include "llvm/Analysis/LoopInfo.h"
Anton Korobeynikove641b522009-08-05 09:29:56 +000033#include "llvm/Analysis/ValueTracking.h"
Gordon Henriksence224772008-01-07 01:30:38 +000034#include "llvm/CodeGen/Passes.h"
Chris Lattner30483732004-06-20 07:49:54 +000035#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner45111d12010-01-16 21:57:06 +000036#include "llvm/Target/Mangler.h"
Chris Lattner94f4f8e2004-02-13 23:00:29 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000038#include "llvm/MC/MCAsmInfo.h"
Chris Lattnera46a3442010-01-13 21:12:34 +000039#include "llvm/MC/MCSymbol.h"
Reid Spencer519e2392007-01-29 17:51:02 +000040#include "llvm/Target/TargetData.h"
Daniel Dunbar51b198a2009-07-15 20:24:03 +000041#include "llvm/Target/TargetRegistry.h"
Chris Lattner23e90702003-11-25 20:49:55 +000042#include "llvm/Support/CallSite.h"
Chris Lattnera05e0ec2004-05-09 03:42:48 +000043#include "llvm/Support/CFG.h"
Torok Edwindac237e2009-07-08 20:53:28 +000044#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000045#include "llvm/Support/FormattedStream.h"
Chris Lattner23e90702003-11-25 20:49:55 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000047#include "llvm/Support/InstVisitor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000048#include "llvm/Support/MathExtras.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000049#include "llvm/System/Host.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000051#include <algorithm>
Bill Wendling1a097e32006-12-07 23:41:45 +000052#include <sstream>
Chris Lattner897bf0d2004-02-13 06:18:21 +000053using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000054
Daniel Dunbar0c795d62009-07-25 06:49:55 +000055extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000057 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000058}
Douglas Gregor1555a232009-06-16 20:12:29 +000059
Dan Gohman844731a2008-05-13 00:00:25 +000060namespace {
Chris Lattnerc0dba722010-01-17 18:22:35 +000061 class CBEMCAsmInfo : public MCAsmInfo {
62 public:
Chris Lattner8eeba352010-01-20 06:34:14 +000063 CBEMCAsmInfo() {
Chris Lattnerc0dba722010-01-17 18:22:35 +000064 GlobalPrefix = "";
65 PrivateGlobalPrefix = "";
66 }
67 };
Chris Lattnerf9a05322006-02-13 22:22:42 +000068 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
Chris Lattner68758072004-05-09 06:20:51 +000071 ///
Chris Lattnerf9a05322006-02-13 22:22:42 +000072 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
Devang Patel794fd752007-05-01 21:15:47 +000073 public:
Devang Patel19974732007-05-03 01:11:54 +000074 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +000075 CBackendNameAllUsedStructsAndMergeFunctions()
Dan Gohmanae73dc12008-09-04 17:05:41 +000076 : ModulePass(&ID) {}
Chris Lattner68758072004-05-09 06:20:51 +000077 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
79 }
80
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
83 }
84
Chris Lattnerb12914b2004-09-20 04:48:05 +000085 virtual bool runOnModule(Module &M);
Chris Lattner68758072004-05-09 06:20:51 +000086 };
Misha Brukmand6a29a52005-04-20 16:05:03 +000087
Devang Patel19974732007-05-03 01:11:54 +000088 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +000089
Chris Lattner68758072004-05-09 06:20:51 +000090 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
David Greene71847812009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Reid Spencer519e2392007-01-29 17:51:02 +000094 IntrinsicLowering *IL;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000095 Mangler *Mang;
Chris Lattnercb3ad012004-05-09 20:41:32 +000096 LoopInfo *LI;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000097 const Module *TheModule;
Chris Lattneraf76e592009-08-22 20:48:53 +000098 const MCAsmInfo* TAsm;
Reid Spencer519e2392007-01-29 17:51:02 +000099 const TargetData* TD;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000100 std::map<const Type *, std::string> TypeNames;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000101 std::map<const ConstantFP *, unsigned> FPConstantMap;
Reid Spencer69f80a62007-04-12 21:00:45 +0000102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattnere05252b42008-03-02 08:07:24 +0000103 std::set<const Argument*> ByValParams;
Chris Lattneraecc22a2008-10-22 04:53:16 +0000104 unsigned FPCounter;
Owen Anderson52132bf2009-06-26 19:48:37 +0000105 unsigned OpaqueCounter;
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
Reid Spencer69f80a62007-04-12 21:00:45 +0000108
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000109 public:
Devang Patel19974732007-05-03 01:11:54 +0000110 static char ID;
David Greene71847812009-07-14 20:18:05 +0000111 explicit CWriter(formatted_raw_ostream &o)
Dan Gohmanae73dc12008-09-04 17:05:41 +0000112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
Chris Lattneraecc22a2008-10-22 04:53:16 +0000114 FPCounter = 0;
115 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000116
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000117 virtual const char *getPassName() const { return "C backend"; }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000118
Chris Lattnercb3ad012004-05-09 20:41:32 +0000119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
122 }
123
Chris Lattner68758072004-05-09 06:20:51 +0000124 virtual bool doInitialization(Module &M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000125
Chris Lattner68758072004-05-09 06:20:51 +0000126 bool runOnFunction(Function &F) {
Chris Lattner9062d9a2009-04-17 00:26:12 +0000127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
130 return false;
131
Chris Lattnercb3ad012004-05-09 20:41:32 +0000132 LI = &getAnalysis<LoopInfo>();
133
Chris Lattner3150e2d2004-12-05 06:49:44 +0000134 // Get rid of intrinsics we can't handle.
135 lowerIntrinsics(F);
136
Chris Lattner68758072004-05-09 06:20:51 +0000137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
Chris Lattner3150e2d2004-12-05 06:49:44 +0000139
Chris Lattner68758072004-05-09 06:20:51 +0000140 printFunction(F);
Chris Lattner68758072004-05-09 06:20:51 +0000141 return false;
142 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000143
Chris Lattner68758072004-05-09 06:20:51 +0000144 virtual bool doFinalization(Module &M) {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000145 // Free memory...
Nuno Lopesbb6382e2009-01-13 23:35:49 +0000146 delete IL;
147 delete TD;
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000148 delete Mang;
Evan Cheng588c6f82008-01-11 09:12:49 +0000149 FPConstantMap.clear();
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000150 TypeNames.clear();
Evan Cheng588c6f82008-01-11 09:12:49 +0000151 ByValParams.clear();
Chris Lattnere05252b42008-03-02 08:07:24 +0000152 intrinsicPrototypesAlreadyGenerated.clear();
Chris Lattnercb3ad012004-05-09 20:41:32 +0000153 return false;
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000154 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000155
David Greene71847812009-07-14 20:18:05 +0000156 raw_ostream &printType(formatted_raw_ostream &Out,
157 const Type *Ty,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
Owen Andersoncb371882008-08-21 00:14:44 +0000162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
Devang Patel05988662008-09-25 21:00:45 +0000166 const AttrListPtr &PAL = AttrListPtr());
David Greene71847812009-07-14 20:18:05 +0000167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
168 const Type *Ty,
169 bool isSigned,
170 const std::string &NameSoFar = "");
Owen Andersoncb371882008-08-21 00:14:44 +0000171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
172 bool isSigned,
173 const std::string &NameSoFar = "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000174
David Greene71847812009-07-14 20:18:05 +0000175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000176 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000177 const PointerType *Ty);
Chris Lattnere05252b42008-03-02 08:07:24 +0000178
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
186 } else {
187 Out << "*(";
188 writeOperand(Operand);
189 Out << ")";
190 }
191 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000192
Dan Gohman9f8d5712008-07-24 17:57:48 +0000193 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnere56d9462008-05-31 09:23:55 +0000194 void writeInstComputationInline(Instruction &I);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000195 void writeOperandInternal(Value *Operand, bool Static = false);
Reid Spencer1628cec2006-10-26 06:15:43 +0000196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner5bda9e42007-09-15 06:51:03 +0000197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000198 bool writeInstructionCast(const Instruction &I);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000199
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +0000200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
202
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000203 private :
Andrew Lenharthe0cf0752006-11-28 19:53:36 +0000204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
205
Chris Lattnerc2421432004-05-09 04:30:20 +0000206 void lowerIntrinsics(Function &F);
Chris Lattner4ef51372004-02-14 00:31:10 +0000207
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000208 void printModule(Module *M);
Reid Spencer78d033e2007-01-06 07:24:44 +0000209 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman193c2352008-06-02 21:30:49 +0000210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Chris Lattner68758072004-05-09 06:20:51 +0000211 void printFloatingPointConstants(Function &F);
Chris Lattneraecc22a2008-10-22 04:53:16 +0000212 void printFloatingPointConstants(const Constant *C);
Chris Lattner4cda8352002-08-20 16:55:48 +0000213 void printFunctionSignature(const Function *F, bool Prototype);
214
Chris Lattner94f4f8e2004-02-13 23:00:29 +0000215 void printFunction(Function &);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000218
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000220 void printConstant(Constant *CPV, bool Static);
Reid Spencer1628cec2006-10-26 06:15:43 +0000221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohman9f8d5712008-07-24 17:57:48 +0000222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000225
Chris Lattnere05252b42008-03-02 08:07:24 +0000226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
233 }
234
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
239 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000240 static bool isInlinableInst(const Instruction &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000241 // Always inline cmp instructions, even if they are shared by multiple
Chris Lattner433e25a2004-05-20 20:25:50 +0000242 // expressions. GCC generates horrible code if we don't.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000243 if (isa<CmpInst>(I))
244 return true;
Chris Lattner433e25a2004-05-20 20:25:50 +0000245
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
Owen Anderson1d0be152009-08-13 21:58:54 +0000248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Misha Brukmand6a29a52005-04-20 16:05:03 +0000249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman193c2352008-06-02 21:30:49 +0000250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
Chris Lattnerd4e8d312003-07-23 20:45:31 +0000252 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000253 return false;
254
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000255 // Must not be used in inline asm, extractelement, or shufflevector.
256 if (I.hasOneUse()) {
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
260 return false;
261 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000262
Reid Spencer555a0b12006-12-11 20:39:15 +0000263 // Only inline instruction it if it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000265 }
266
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
270 //
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000277 return 0;
278 return AI;
279 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000280
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
284 return true;
285 return false;
286 }
287
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000290
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000293 void visitSwitchInst(SwitchInst &I);
Chris Lattnerab21db72009-10-28 00:19:10 +0000294 void visitIndirectBrInst(IndirectBrInst &I);
Chris Lattnercb3ad012004-05-09 20:41:32 +0000295 void visitInvokeInst(InvokeInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000296 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000297 }
298
299 void visitUnwindInst(UnwindInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000300 llvm_unreachable("Lowerinvoke pass didn't work!");
Chris Lattnercb3ad012004-05-09 20:41:32 +0000301 }
Chris Lattnera9d12c02004-10-16 18:12:13 +0000302 void visitUnreachableInst(UnreachableInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000303
Chris Lattner84e66652003-05-03 07:11:00 +0000304 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000305 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000308
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000309 void visitCastInst (CastInst &I);
Chris Lattner9f24a072004-03-12 05:52:14 +0000310 void visitSelectInst(SelectInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000311 void visitCallInst (CallInst &I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +0000312 void visitInlineAsm(CallInst &I);
Chris Lattner2299fec2008-03-02 08:29:41 +0000313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000314
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000315 void visitAllocaInst(AllocaInst &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner4d45bd02003-10-18 05:57:43 +0000319 void visitVAArgInst (VAArgInst &I);
Chris Lattner33a44d92008-03-02 03:52:39 +0000320
321 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner0452ed62008-03-02 03:57:08 +0000322 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerb1855ad2008-03-02 05:41:07 +0000323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000324
Dan Gohman193c2352008-06-02 21:30:49 +0000325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000328 void visitInstruction(Instruction &I) {
Torok Edwindac237e2009-07-08 20:53:28 +0000329#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000330 errs() << "C Writer does not know about " << I;
Torok Edwindac237e2009-07-08 20:53:28 +0000331#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000332 llvm_unreachable(0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000333 }
334
335 void outputLValue(Instruction *I) {
Bill Wendling145aad02007-02-23 22:45:08 +0000336 Out << " " << GetValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000337 }
Chris Lattnercb3ad012004-05-09 20:41:32 +0000338
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
John Criswell57bbfce2004-10-20 14:38:39 +0000340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
343 unsigned Indent);
Chris Lattnere05252b42008-03-02 08:07:24 +0000344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +0000345 gep_type_iterator E, bool Static);
Bill Wendling145aad02007-02-23 22:45:08 +0000346
347 std::string GetValueName(const Value *Operand);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000348 };
Chris Lattner4ef51372004-02-14 00:31:10 +0000349}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000350
Devang Patel19974732007-05-03 01:11:54 +0000351char CWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000352
Chris Lattner471f1e92010-01-13 19:54:07 +0000353
Chris Lattner7481ae62010-01-22 18:33:00 +0000354static std::string CBEMangle(const std::string &S) {
Chris Lattner0bd58b02010-01-17 19:32:29 +0000355 std::string Result;
356
357 for (unsigned i = 0, e = S.size(); i != e; ++i)
358 if (isalnum(S[i]) || S[i] == '_') {
359 Result += S[i];
360 } else {
361 Result += '_';
362 Result += 'A'+(S[i]&15);
363 Result += 'A'+((S[i]>>4)&15);
364 Result += '_';
365 }
366 return Result;
Chris Lattner471f1e92010-01-13 19:54:07 +0000367}
368
369
Chris Lattner68758072004-05-09 06:20:51 +0000370/// This method inserts names for any unnamed structure types that are used by
371/// the program, and removes names from structure types that are not used by the
372/// program.
373///
Chris Lattnerf9a05322006-02-13 22:22:42 +0000374bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
Chris Lattner68758072004-05-09 06:20:51 +0000375 // Get a set of types that are used by the program...
376 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000377
Chris Lattner68758072004-05-09 06:20:51 +0000378 // Loop over the module symbol table, removing types from UT that are
Chris Lattnerdbf69f12005-03-08 16:19:59 +0000379 // already named, and removing names for types that are not used.
Chris Lattner68758072004-05-09 06:20:51 +0000380 //
Reid Spencer78d033e2007-01-06 07:24:44 +0000381 TypeSymbolTable &TST = M.getTypeSymbolTable();
382 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
Reid Spencer9231ac82004-05-25 08:53:40 +0000383 TI != TE; ) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000384 TypeSymbolTable::iterator I = TI++;
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000385
Dan Gohman193c2352008-06-02 21:30:49 +0000386 // If this isn't a struct or array type, remove it from our set of types
387 // to name. This simplifies emission later.
388 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
389 !isa<ArrayType>(I->second)) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000390 TST.remove(I);
Chris Lattner19e8b0c2007-01-16 07:22:23 +0000391 } else {
392 // If this is not used, remove it from the symbol table.
393 std::set<const Type *>::iterator UTI = UT.find(I->second);
394 if (UTI == UT.end())
395 TST.remove(I);
396 else
397 UT.erase(UTI); // Only keep one name for this type.
398 }
Reid Spencer9231ac82004-05-25 08:53:40 +0000399 }
Chris Lattner68758072004-05-09 06:20:51 +0000400
401 // UT now contains types that are not named. Loop over it, naming
402 // structure types.
403 //
404 bool Changed = false;
Chris Lattner9d1af972004-05-28 05:47:27 +0000405 unsigned RenameCounter = 0;
Chris Lattner68758072004-05-09 06:20:51 +0000406 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
407 I != E; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +0000408 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
409 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Chris Lattner9d1af972004-05-28 05:47:27 +0000410 ++RenameCounter;
Chris Lattner68758072004-05-09 06:20:51 +0000411 Changed = true;
412 }
Chris Lattnerf9a05322006-02-13 22:22:42 +0000413
414
415 // Loop over all external functions and globals. If we have two with
416 // identical names, merge them.
417 // FIXME: This code should disappear when we don't allow values with the same
418 // names when they have different types!
419 std::map<std::string, GlobalValue*> ExtSymbols;
420 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
421 Function *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000422 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000423 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
424 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
425 if (!X.second) {
426 // Found a conflict, replace this global with the previous one.
427 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000428 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000429 GV->eraseFromParent();
430 Changed = true;
431 }
432 }
433 }
434 // Do the same for globals.
435 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
436 I != E;) {
437 GlobalVariable *GV = I++;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000438 if (GV->isDeclaration() && GV->hasName()) {
Chris Lattnerf9a05322006-02-13 22:22:42 +0000439 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
440 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
441 if (!X.second) {
442 // Found a conflict, replace this global with the previous one.
443 GlobalValue *OldGV = X.first->second;
Reid Spencer4da49122006-12-12 05:05:00 +0000444 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
Chris Lattnerf9a05322006-02-13 22:22:42 +0000445 GV->eraseFromParent();
446 Changed = true;
447 }
448 }
449 }
450
Chris Lattner68758072004-05-09 06:20:51 +0000451 return Changed;
452}
453
Chris Lattner0c54d892006-05-23 23:39:48 +0000454/// printStructReturnPointerFunctionType - This is like printType for a struct
455/// return type, except, instead of printing the type as void (*)(Struct*, ...)
456/// print it as "Struct (*)(...)", for struct return functions.
David Greene71847812009-07-14 20:18:05 +0000457void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Patel05988662008-09-25 21:00:45 +0000458 const AttrListPtr &PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +0000459 const PointerType *TheTy) {
460 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
461 std::stringstream FunctionInnards;
462 FunctionInnards << " (*) (";
463 bool PrintedType = false;
464
465 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
466 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
Reid Spencer0ae96932007-01-07 03:24:48 +0000467 unsigned Idx = 1;
Evan Cheng681d2b82008-01-11 03:07:46 +0000468 for (++I, ++Idx; I != E; ++I, ++Idx) {
Chris Lattner0c54d892006-05-23 23:39:48 +0000469 if (PrintedType)
470 FunctionInnards << ", ";
Evan Cheng681d2b82008-01-11 03:07:46 +0000471 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000472 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +0000473 assert(isa<PointerType>(ArgTy));
474 ArgTy = cast<PointerType>(ArgTy)->getElementType();
475 }
Evan Cheng681d2b82008-01-11 03:07:46 +0000476 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000477 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Chris Lattner0c54d892006-05-23 23:39:48 +0000478 PrintedType = true;
479 }
480 if (FTy->isVarArg()) {
481 if (PrintedType)
482 FunctionInnards << ", ...";
483 } else if (!PrintedType) {
484 FunctionInnards << "void";
485 }
486 FunctionInnards << ')';
487 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000488 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +0000489 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Chris Lattner0c54d892006-05-23 23:39:48 +0000490}
491
Owen Andersoncb371882008-08-21 00:14:44 +0000492raw_ostream &
David Greene71847812009-07-14 20:18:05 +0000493CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
494 bool isSigned,
Owen Andersoncb371882008-08-21 00:14:44 +0000495 const std::string &NameSoFar) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000496 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) &&
Owen Andersoncb371882008-08-21 00:14:44 +0000497 "Invalid type for printSimpleType");
498 switch (Ty->getTypeID()) {
499 case Type::VoidTyID: return Out << "void " << NameSoFar;
500 case Type::IntegerTyID: {
501 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
502 if (NumBits == 1)
503 return Out << "bool " << NameSoFar;
504 else if (NumBits <= 8)
505 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
506 else if (NumBits <= 16)
507 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
508 else if (NumBits <= 32)
509 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
510 else if (NumBits <= 64)
511 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
512 else {
513 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
514 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
515 }
516 }
517 case Type::FloatTyID: return Out << "float " << NameSoFar;
518 case Type::DoubleTyID: return Out << "double " << NameSoFar;
519 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
520 // present matches host 'long double'.
521 case Type::X86_FP80TyID:
522 case Type::PPC_FP128TyID:
523 case Type::FP128TyID: return Out << "long double " << NameSoFar;
524
525 case Type::VectorTyID: {
526 const VectorType *VTy = cast<VectorType>(Ty);
527 return printSimpleType(Out, VTy->getElementType(), isSigned,
528 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000529 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Andersoncb371882008-08-21 00:14:44 +0000530 }
531
532 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000533#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000534 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000535#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000536 llvm_unreachable(0);
Owen Andersoncb371882008-08-21 00:14:44 +0000537 }
538}
539
Reid Spencere4d87aa2006-12-23 06:05:41 +0000540std::ostream &
Reid Spencera54b7cb2007-01-12 07:05:14 +0000541CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattner90683ab2008-03-02 03:41:23 +0000542 const std::string &NameSoFar) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000543 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) &&
Reid Spencera54b7cb2007-01-12 07:05:14 +0000544 "Invalid type for printSimpleType");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000545 switch (Ty->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000546 case Type::VoidTyID: return Out << "void " << NameSoFar;
547 case Type::IntegerTyID: {
548 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
549 if (NumBits == 1)
550 return Out << "bool " << NameSoFar;
551 else if (NumBits <= 8)
552 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
553 else if (NumBits <= 16)
554 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
555 else if (NumBits <= 32)
556 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000557 else if (NumBits <= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000558 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmand7614802008-04-02 19:40:14 +0000559 else {
560 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
561 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000562 }
563 }
564 case Type::FloatTyID: return Out << "float " << NameSoFar;
565 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000566 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
567 // present matches host 'long double'.
568 case Type::X86_FP80TyID:
569 case Type::PPC_FP128TyID:
570 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000571
572 case Type::VectorTyID: {
573 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner90683ab2008-03-02 03:41:23 +0000574 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattner32cba8e2008-03-02 03:39:43 +0000575 " __attribute__((vector_size(" +
Duncan Sands777d2302009-05-09 07:06:46 +0000576 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000577 }
578
579 default:
Torok Edwindac237e2009-07-08 20:53:28 +0000580#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000581 errs() << "Unknown primitive type: " << *Ty << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +0000582#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000583 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000584 }
585}
Chris Lattner68758072004-05-09 06:20:51 +0000586
Chris Lattner83c57752002-08-19 22:17:53 +0000587// Pass the Type* and the variable name and this prints out the variable
588// declaration.
589//
David Greene71847812009-07-14 20:18:05 +0000590raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
591 const Type *Ty,
592 bool isSigned, const std::string &NameSoFar,
593 bool IgnoreName, const AttrListPtr &PAL) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000594 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) {
Owen Andersoncb371882008-08-21 00:14:44 +0000595 printSimpleType(Out, Ty, isSigned, NameSoFar);
596 return Out;
597 }
598
599 // Check to see if the type is named.
600 if (!IgnoreName || isa<OpaqueType>(Ty)) {
601 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
602 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
603 }
604
605 switch (Ty->getTypeID()) {
606 case Type::FunctionTyID: {
607 const FunctionType *FTy = cast<FunctionType>(Ty);
608 std::stringstream FunctionInnards;
609 FunctionInnards << " (" << NameSoFar << ") (";
610 unsigned Idx = 1;
611 for (FunctionType::param_iterator I = FTy->param_begin(),
612 E = FTy->param_end(); I != E; ++I) {
613 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000614 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Andersoncb371882008-08-21 00:14:44 +0000615 assert(isa<PointerType>(ArgTy));
616 ArgTy = cast<PointerType>(ArgTy)->getElementType();
617 }
618 if (I != FTy->param_begin())
619 FunctionInnards << ", ";
620 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000621 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Andersoncb371882008-08-21 00:14:44 +0000622 ++Idx;
623 }
624 if (FTy->isVarArg()) {
625 if (FTy->getNumParams())
626 FunctionInnards << ", ...";
627 } else if (!FTy->getNumParams()) {
628 FunctionInnards << "void";
629 }
630 FunctionInnards << ')';
631 std::string tstr = FunctionInnards.str();
632 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000633 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Andersoncb371882008-08-21 00:14:44 +0000634 return Out;
635 }
636 case Type::StructTyID: {
637 const StructType *STy = cast<StructType>(Ty);
638 Out << NameSoFar + " {\n";
639 unsigned Idx = 0;
640 for (StructType::element_iterator I = STy->element_begin(),
641 E = STy->element_end(); I != E; ++I) {
642 Out << " ";
643 printType(Out, *I, false, "field" + utostr(Idx++));
644 Out << ";\n";
645 }
646 Out << '}';
647 if (STy->isPacked())
648 Out << " __attribute__ ((packed))";
649 return Out;
650 }
651
652 case Type::PointerTyID: {
653 const PointerType *PTy = cast<PointerType>(Ty);
654 std::string ptrName = "*" + NameSoFar;
655
656 if (isa<ArrayType>(PTy->getElementType()) ||
657 isa<VectorType>(PTy->getElementType()))
658 ptrName = "(" + ptrName + ")";
659
660 if (!PAL.isEmpty())
661 // Must be a function ptr cast!
662 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
663 return printType(Out, PTy->getElementType(), false, ptrName);
664 }
665
666 case Type::ArrayTyID: {
667 const ArrayType *ATy = cast<ArrayType>(Ty);
668 unsigned NumElements = ATy->getNumElements();
669 if (NumElements == 0) NumElements = 1;
670 // Arrays are wrapped in structs to allow them to have normal
671 // value semantics (avoiding the array "decay").
672 Out << NameSoFar << " { ";
673 printType(Out, ATy->getElementType(), false,
674 "array[" + utostr(NumElements) + "]");
675 return Out << "; }";
676 }
677
678 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000679 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Andersoncb371882008-08-21 00:14:44 +0000680 assert(TypeNames.find(Ty) == TypeNames.end());
681 TypeNames[Ty] = TyName;
682 return Out << TyName << ' ' << NameSoFar;
683 }
684 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000685 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Andersoncb371882008-08-21 00:14:44 +0000686 }
687
688 return Out;
689}
690
691// Pass the Type* and the variable name and this prints out the variable
692// declaration.
693//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000694std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
Reid Spencer0ae96932007-01-07 03:24:48 +0000695 bool isSigned, const std::string &NameSoFar,
Devang Patel05988662008-09-25 21:00:45 +0000696 bool IgnoreName, const AttrListPtr &PAL) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000697 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<VectorType>(Ty)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000698 printSimpleType(Out, Ty, isSigned, NameSoFar);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000699 return Out;
700 }
Misha Brukmand6a29a52005-04-20 16:05:03 +0000701
Chris Lattner83c57752002-08-19 22:17:53 +0000702 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000703 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000704 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000705 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000706 }
Chris Lattner83c57752002-08-19 22:17:53 +0000707
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000708 switch (Ty->getTypeID()) {
Chris Lattner83c57752002-08-19 22:17:53 +0000709 case Type::FunctionTyID: {
Chris Lattner0c54d892006-05-23 23:39:48 +0000710 const FunctionType *FTy = cast<FunctionType>(Ty);
Misha Brukmand6a29a52005-04-20 16:05:03 +0000711 std::stringstream FunctionInnards;
Joel Stanley54f60322003-06-25 04:52:09 +0000712 FunctionInnards << " (" << NameSoFar << ") (";
Reid Spencer0ae96932007-01-07 03:24:48 +0000713 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +0000714 for (FunctionType::param_iterator I = FTy->param_begin(),
715 E = FTy->param_end(); I != E; ++I) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000716 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +0000717 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng7723ab32008-01-12 18:53:07 +0000718 assert(isa<PointerType>(ArgTy));
719 ArgTy = cast<PointerType>(ArgTy)->getElementType();
720 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000721 if (I != FTy->param_begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000722 FunctionInnards << ", ";
Evan Cheng7723ab32008-01-12 18:53:07 +0000723 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +0000724 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Reid Spencer0ae96932007-01-07 03:24:48 +0000725 ++Idx;
Chris Lattner83c57752002-08-19 22:17:53 +0000726 }
Chris Lattner0c54d892006-05-23 23:39:48 +0000727 if (FTy->isVarArg()) {
728 if (FTy->getNumParams())
Reid Spencer9231ac82004-05-25 08:53:40 +0000729 FunctionInnards << ", ...";
Chris Lattner0c54d892006-05-23 23:39:48 +0000730 } else if (!FTy->getNumParams()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000731 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000732 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000733 FunctionInnards << ')';
Joel Stanley54f60322003-06-25 04:52:09 +0000734 std::string tstr = FunctionInnards.str();
Reid Spencer0ae96932007-01-07 03:24:48 +0000735 printType(Out, FTy->getReturnType(),
Devang Patel05988662008-09-25 21:00:45 +0000736 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000737 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000738 }
739 case Type::StructTyID: {
740 const StructType *STy = cast<StructType>(Ty);
741 Out << NameSoFar + " {\n";
742 unsigned Idx = 0;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000743 for (StructType::element_iterator I = STy->element_begin(),
744 E = STy->element_end(); I != E; ++I) {
Chris Lattner83c57752002-08-19 22:17:53 +0000745 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +0000746 printType(Out, *I, false, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000747 Out << ";\n";
748 }
Lauro Ramos Venancioa126bb72007-07-11 19:56:53 +0000749 Out << '}';
750 if (STy->isPacked())
751 Out << " __attribute__ ((packed))";
752 return Out;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000753 }
Chris Lattner83c57752002-08-19 22:17:53 +0000754
755 case Type::PointerTyID: {
756 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000757 std::string ptrName = "*" + NameSoFar;
758
Robert Bocchinob78e8382006-01-20 20:43:57 +0000759 if (isa<ArrayType>(PTy->getElementType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +0000760 isa<VectorType>(PTy->getElementType()))
Chris Lattner8917d362003-11-03 04:31:54 +0000761 ptrName = "(" + ptrName + ")";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000762
Chris Lattner58d74912008-03-12 17:45:29 +0000763 if (!PAL.isEmpty())
Evan Cheng7723ab32008-01-12 18:53:07 +0000764 // Must be a function ptr cast!
765 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Reid Spencer251f2142007-01-09 17:09:09 +0000766 return printType(Out, PTy->getElementType(), false, ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000767 }
Chris Lattner83c57752002-08-19 22:17:53 +0000768
769 case Type::ArrayTyID: {
770 const ArrayType *ATy = cast<ArrayType>(Ty);
771 unsigned NumElements = ATy->getNumElements();
Chris Lattner3e3b6f72004-12-15 23:13:15 +0000772 if (NumElements == 0) NumElements = 1;
Dan Gohman193c2352008-06-02 21:30:49 +0000773 // Arrays are wrapped in structs to allow them to have normal
774 // value semantics (avoiding the array "decay").
775 Out << NameSoFar << " { ";
776 printType(Out, ATy->getElementType(), false,
777 "array[" + utostr(NumElements) + "]");
778 return Out << "; }";
Chris Lattner83c57752002-08-19 22:17:53 +0000779 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000780
781 case Type::OpaqueTyID: {
Owen Anderson52132bf2009-06-26 19:48:37 +0000782 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000783 assert(TypeNames.find(Ty) == TypeNames.end());
784 TypeNames[Ty] = TyName;
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000785 return Out << TyName << ' ' << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000786 }
Chris Lattner83c57752002-08-19 22:17:53 +0000787 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000788 llvm_unreachable("Unhandled case in getTypeProps!");
Chris Lattner83c57752002-08-19 22:17:53 +0000789 }
790
791 return Out;
792}
793
Dan Gohman9f8d5712008-07-24 17:57:48 +0000794void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000795
796 // As a special case, print the array as a string if it is an array of
797 // ubytes or an array of sbytes with positive values.
Misha Brukmand6a29a52005-04-20 16:05:03 +0000798 //
Chris Lattner6d492922002-08-19 21:32:41 +0000799 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000800 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
801 ETy == Type::getInt8Ty(CPA->getContext()));
Chris Lattner6d492922002-08-19 21:32:41 +0000802
803 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000804 if (isString && (CPA->getNumOperands() == 0 ||
805 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000806 isString = false;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000807
Chris Lattner6d492922002-08-19 21:32:41 +0000808 if (isString) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000809 Out << '\"';
Chris Lattner02da6c02003-06-16 12:09:09 +0000810 // Keep track of whether the last number was a hexadecimal escape
811 bool LastWasHex = false;
812
Chris Lattner6d492922002-08-19 21:32:41 +0000813 // Do not include the last character, which we know is null
814 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000815 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +0000816
Chris Lattner02da6c02003-06-16 12:09:09 +0000817 // Print it out literally if it is a printable character. The only thing
818 // to be careful about is when the last letter output was a hex escape
819 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000820 // explicitly (the C compiler thinks it is a continuation of the previous
821 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000822 //
823 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
824 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000825 if (C == '"' || C == '\\')
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000826 Out << "\\" << (char)C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000827 else
Chris Lattner1f0f37a2008-08-21 05:51:43 +0000828 Out << (char)C;
Chris Lattner6d492922002-08-19 21:32:41 +0000829 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000830 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000831 switch (C) {
832 case '\n': Out << "\\n"; break;
833 case '\t': Out << "\\t"; break;
834 case '\r': Out << "\\r"; break;
835 case '\v': Out << "\\v"; break;
836 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000837 case '\"': Out << "\\\""; break;
Misha Brukmand6a29a52005-04-20 16:05:03 +0000838 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000839 default:
840 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000841 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
842 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
843 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000844 break;
845 }
846 }
847 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000848 Out << '\"';
Chris Lattner6d492922002-08-19 21:32:41 +0000849 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000850 Out << '{';
Chris Lattner6d492922002-08-19 21:32:41 +0000851 if (CPA->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +0000852 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000853 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000854 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
855 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000856 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Chris Lattner6d492922002-08-19 21:32:41 +0000857 }
858 }
859 Out << " }";
860 }
861}
862
Dan Gohman9f8d5712008-07-24 17:57:48 +0000863void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Robert Bocchinob78e8382006-01-20 20:43:57 +0000864 Out << '{';
865 if (CP->getNumOperands()) {
866 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +0000867 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000868 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
869 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +0000870 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +0000871 }
872 }
873 Out << " }";
874}
875
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000876// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
877// textually as a double (rather than as a reference to a stack-allocated
878// variable). We decide this by converting CFP to a string and back into a
879// double, and then checking whether the conversion results in a bit-equal
880// double to the original value of CFP. This depends on us and the target C
881// compiler agreeing on the conversion process (which is pretty likely since we
882// only deal in IEEE FP).
883//
Chris Lattnercb3ad012004-05-09 20:41:32 +0000884static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000885 bool ignored;
Dale Johannesen53f0bc12007-09-17 00:38:27 +0000886 // Do long doubles in hex for now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000887 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
888 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000889 return false;
Dale Johannesen43421b32007-09-06 18:13:44 +0000890 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000891 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000892 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Reid Spencerbcf81242006-11-05 19:26:37 +0000893#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000894 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +0000895 sprintf(Buffer, "%a", APF.convertToDouble());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000896 if (!strncmp(Buffer, "0x", 2) ||
897 !strncmp(Buffer, "-0x", 3) ||
898 !strncmp(Buffer, "+0x", 3))
Dale Johannesen43421b32007-09-06 18:13:44 +0000899 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000900 return false;
901#else
Dale Johannesen43421b32007-09-06 18:13:44 +0000902 std::string StrVal = ftostr(APF);
Chris Lattner9860e772003-10-12 04:36:29 +0000903
904 while (StrVal[0] == ' ')
905 StrVal.erase(StrVal.begin());
906
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000907 // Check to make sure that the stringized number is not some string like "Inf"
908 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000909 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
910 ((StrVal[0] == '-' || StrVal[0] == '+') &&
911 (StrVal[1] >= '0' && StrVal[1] <= '9')))
912 // Reparse stringized version!
Dale Johannesen43421b32007-09-06 18:13:44 +0000913 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Brian Gaekeb471a232003-06-17 23:55:35 +0000914 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000915#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000916}
Chris Lattner6d492922002-08-19 21:32:41 +0000917
Reid Spencer3da59db2006-11-27 01:05:10 +0000918/// Print out the casting for a cast operation. This does the double casting
919/// necessary for conversion to the destination type, if necessary.
Reid Spencer3da59db2006-11-27 01:05:10 +0000920/// @brief Print a cast
921void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000922 // Print the destination type cast
923 switch (opc) {
924 case Instruction::UIToFP:
925 case Instruction::SIToFP:
926 case Instruction::IntToPtr:
927 case Instruction::Trunc:
928 case Instruction::BitCast:
929 case Instruction::FPExt:
930 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
931 Out << '(';
932 printType(Out, DstTy);
933 Out << ')';
934 break;
935 case Instruction::ZExt:
936 case Instruction::PtrToInt:
937 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
938 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000939 printSimpleType(Out, DstTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000940 Out << ')';
941 break;
942 case Instruction::SExt:
943 case Instruction::FPToSI: // For these, make sure we get a signed dest
944 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000945 printSimpleType(Out, DstTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000946 Out << ')';
947 break;
948 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000949 llvm_unreachable("Invalid cast opcode");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000950 }
951
952 // Print the source type cast
Reid Spencer3da59db2006-11-27 01:05:10 +0000953 switch (opc) {
954 case Instruction::UIToFP:
955 case Instruction::ZExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000956 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000957 printSimpleType(Out, SrcTy, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000958 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000959 break;
960 case Instruction::SIToFP:
961 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000962 Out << '(';
Reid Spencera54b7cb2007-01-12 07:05:14 +0000963 printSimpleType(Out, SrcTy, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000964 Out << ')';
Reid Spencer3da59db2006-11-27 01:05:10 +0000965 break;
966 case Instruction::IntToPtr:
967 case Instruction::PtrToInt:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000968 // Avoid "cast to pointer from integer of different size" warnings
969 Out << "(unsigned long)";
970 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000971 case Instruction::Trunc:
972 case Instruction::BitCast:
973 case Instruction::FPExt:
974 case Instruction::FPTrunc:
975 case Instruction::FPToSI:
976 case Instruction::FPToUI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000977 break; // These don't need a source cast.
Reid Spencer3da59db2006-11-27 01:05:10 +0000978 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000979 llvm_unreachable("Invalid cast opcode");
Reid Spencer3da59db2006-11-27 01:05:10 +0000980 break;
981 }
982}
983
Chris Lattner6d492922002-08-19 21:32:41 +0000984// printConstant - The LLVM Constant to C Constant converter.
Dan Gohman9f8d5712008-07-24 17:57:48 +0000985void CWriter::printConstant(Constant *CPV, bool Static) {
Chris Lattner6d492922002-08-19 21:32:41 +0000986 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
987 switch (CE->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000988 case Instruction::Trunc:
989 case Instruction::ZExt:
990 case Instruction::SExt:
991 case Instruction::FPTrunc:
992 case Instruction::FPExt:
993 case Instruction::UIToFP:
994 case Instruction::SIToFP:
995 case Instruction::FPToUI:
996 case Instruction::FPToSI:
997 case Instruction::PtrToInt:
998 case Instruction::IntToPtr:
999 case Instruction::BitCast:
1000 Out << "(";
1001 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
Chris Lattner72623362007-05-03 02:57:13 +00001002 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001003 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Reid Spencercee7ba32007-05-02 02:17:41 +00001004 // Make sure we really sext from bool here by subtracting from 0
1005 Out << "0-";
Reid Spencercee7ba32007-05-02 02:17:41 +00001006 }
Dan Gohman9f8d5712008-07-24 17:57:48 +00001007 printConstant(CE->getOperand(0), Static);
Owen Anderson1d0be152009-08-13 21:58:54 +00001008 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Chris Lattner72623362007-05-03 02:57:13 +00001009 (CE->getOpcode() == Instruction::Trunc ||
1010 CE->getOpcode() == Instruction::FPToUI ||
1011 CE->getOpcode() == Instruction::FPToSI ||
1012 CE->getOpcode() == Instruction::PtrToInt)) {
1013 // Make sure we really truncate to bool here by anding with 1
1014 Out << "&1u";
1015 }
1016 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001017 return;
Chris Lattner72623362007-05-03 02:57:13 +00001018
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001019 case Instruction::GetElementPtr:
Chris Lattnere05252b42008-03-02 08:07:24 +00001020 Out << "(";
1021 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohman9f8d5712008-07-24 17:57:48 +00001022 gep_type_end(CPV), Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00001023 Out << ")";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001024 return;
Chris Lattner6683dbf2004-04-01 05:28:26 +00001025 case Instruction::Select:
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001026 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001027 printConstant(CE->getOperand(0), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001028 Out << '?';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001029 printConstant(CE->getOperand(1), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001030 Out << ':';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001031 printConstant(CE->getOperand(2), Static);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001032 Out << ')';
Chris Lattner6683dbf2004-04-01 05:28:26 +00001033 return;
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001034 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001035 case Instruction::FAdd:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001036 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001037 case Instruction::FSub:
Chris Lattner29255922003-08-14 19:19:53 +00001038 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001039 case Instruction::FMul:
Reid Spencer1628cec2006-10-26 06:15:43 +00001040 case Instruction::SDiv:
1041 case Instruction::UDiv:
1042 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001043 case Instruction::URem:
1044 case Instruction::SRem:
1045 case Instruction::FRem:
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001046 case Instruction::And:
1047 case Instruction::Or:
1048 case Instruction::Xor:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001049 case Instruction::ICmp:
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001050 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001051 case Instruction::LShr:
1052 case Instruction::AShr:
Reid Spencer72ddc212006-10-26 06:17:40 +00001053 {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001054 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001055 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencer1628cec2006-10-26 06:15:43 +00001056 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
Chris Lattner29255922003-08-14 19:19:53 +00001057 switch (CE->getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001058 case Instruction::Add:
1059 case Instruction::FAdd: Out << " + "; break;
1060 case Instruction::Sub:
1061 case Instruction::FSub: Out << " - "; break;
1062 case Instruction::Mul:
1063 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001064 case Instruction::URem:
1065 case Instruction::SRem:
1066 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001067 case Instruction::UDiv:
1068 case Instruction::SDiv:
1069 case Instruction::FDiv: Out << " / "; break;
Chris Lattnerf376e5e2004-12-29 04:00:09 +00001070 case Instruction::And: Out << " & "; break;
1071 case Instruction::Or: Out << " | "; break;
1072 case Instruction::Xor: Out << " ^ "; break;
Brian Gaeke0415b6c2003-11-22 05:02:56 +00001073 case Instruction::Shl: Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001074 case Instruction::LShr:
1075 case Instruction::AShr: Out << " >> "; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001076 case Instruction::ICmp:
1077 switch (CE->getPredicate()) {
1078 case ICmpInst::ICMP_EQ: Out << " == "; break;
1079 case ICmpInst::ICMP_NE: Out << " != "; break;
1080 case ICmpInst::ICMP_SLT:
1081 case ICmpInst::ICMP_ULT: Out << " < "; break;
1082 case ICmpInst::ICMP_SLE:
1083 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1084 case ICmpInst::ICMP_SGT:
1085 case ICmpInst::ICMP_UGT: Out << " > "; break;
1086 case ICmpInst::ICMP_SGE:
1087 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001088 default: llvm_unreachable("Illegal ICmp predicate");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001089 }
1090 break;
Torok Edwinc23197a2009-07-14 16:55:14 +00001091 default: llvm_unreachable("Illegal opcode here!");
Chris Lattner29255922003-08-14 19:19:53 +00001092 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001093 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1094 if (NeedsClosingParens)
1095 Out << "))";
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001096 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001097 return;
Reid Spencer72ddc212006-10-26 06:17:40 +00001098 }
Reid Spencerb801a272007-01-08 06:58:32 +00001099 case Instruction::FCmp: {
1100 Out << '(';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001101 bool NeedsClosingParens = printConstExprCast(CE, Static);
Reid Spencerb801a272007-01-08 06:58:32 +00001102 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1103 Out << "0";
1104 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1105 Out << "1";
1106 else {
1107 const char* op = 0;
1108 switch (CE->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001109 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00001110 case FCmpInst::FCMP_ORD: op = "ord"; break;
1111 case FCmpInst::FCMP_UNO: op = "uno"; break;
1112 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1113 case FCmpInst::FCMP_UNE: op = "une"; break;
1114 case FCmpInst::FCMP_ULT: op = "ult"; break;
1115 case FCmpInst::FCMP_ULE: op = "ule"; break;
1116 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1117 case FCmpInst::FCMP_UGE: op = "uge"; break;
1118 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1119 case FCmpInst::FCMP_ONE: op = "one"; break;
1120 case FCmpInst::FCMP_OLT: op = "olt"; break;
1121 case FCmpInst::FCMP_OLE: op = "ole"; break;
1122 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1123 case FCmpInst::FCMP_OGE: op = "oge"; break;
1124 }
1125 Out << "llvm_fcmp_" << op << "(";
1126 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1127 Out << ", ";
1128 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1129 Out << ")";
1130 }
1131 if (NeedsClosingParens)
1132 Out << "))";
1133 Out << ')';
Anton Korobeynikovdceadaf2007-12-21 23:33:44 +00001134 return;
Reid Spencerb801a272007-01-08 06:58:32 +00001135 }
Chris Lattner6d492922002-08-19 21:32:41 +00001136 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001137#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001138 errs() << "CWriter Error: Unhandled constant expression: "
Bill Wendlingf5da1332006-12-07 22:21:48 +00001139 << *CE << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001140#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001141 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001142 }
Dan Gohman17dab192008-05-23 16:57:00 +00001143 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Chris Lattner665825e2004-10-17 17:48:59 +00001144 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001145 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerd9a706e2008-03-02 08:14:45 +00001146 Out << ")/*UNDEF*/";
1147 if (!isa<VectorType>(CPV->getType())) {
1148 Out << "0)";
1149 } else {
1150 Out << "{})";
1151 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001152 return;
Chris Lattner6d492922002-08-19 21:32:41 +00001153 }
1154
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001155 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1156 const Type* Ty = CI->getType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001157 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001158 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson1d0be152009-08-13 21:58:54 +00001159 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001160 Out << CI->getZExtValue() << 'u';
1161 else if (Ty->getPrimitiveSizeInBits() > 32)
1162 Out << CI->getZExtValue() << "ull";
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001163 else {
1164 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001165 printSimpleType(Out, Ty, false) << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001166 if (CI->isMinValue(true))
1167 Out << CI->getZExtValue() << 'u';
1168 else
1169 Out << CI->getSExtValue();
Dale Johannesenf4786cc2009-05-19 00:46:42 +00001170 Out << ')';
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001171 }
Reid Spencerfbe7ae92007-01-08 08:00:00 +00001172 return;
1173 }
1174
1175 switch (CPV->getType()->getTypeID()) {
Chris Lattner6d492922002-08-19 21:32:41 +00001176 case Type::FloatTyID:
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001177 case Type::DoubleTyID:
1178 case Type::X86_FP80TyID:
1179 case Type::PPC_FP128TyID:
1180 case Type::FP128TyID: {
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001181 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +00001182 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001183 if (I != FPConstantMap.end()) {
1184 // Because of FP precision problems we must load from a stack allocated
1185 // value that holds the value in hex.
Owen Anderson1d0be152009-08-13 21:58:54 +00001186 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1187 "float" :
1188 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1189 "double" :
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001190 "long double")
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001191 << "*)&FPConstant" << I->second << ')';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001192 } else {
Chris Lattnerabec4742008-10-17 06:11:48 +00001193 double V;
Owen Anderson1d0be152009-08-13 21:58:54 +00001194 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001195 V = FPC->getValueAPF().convertToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +00001196 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnerabec4742008-10-17 06:11:48 +00001197 V = FPC->getValueAPF().convertToDouble();
1198 else {
1199 // Long double. Convert the number to double, discarding precision.
1200 // This is not awesome, but it at least makes the CBE output somewhat
1201 // useful.
1202 APFloat Tmp = FPC->getValueAPF();
1203 bool LosesInfo;
1204 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1205 V = Tmp.convertToDouble();
1206 }
1207
Dale Johannesen43421b32007-09-06 18:13:44 +00001208 if (IsNAN(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001209 // The value is NaN
Misha Brukmand6a29a52005-04-20 16:05:03 +00001210
Dale Johannesen43421b32007-09-06 18:13:44 +00001211 // FIXME the actual NaN bits should be emitted.
Brian Gaeke8a702e82004-08-25 19:00:42 +00001212 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1213 // it's 0x7ff4.
1214 const unsigned long QuietNaN = 0x7ff8UL;
Reid Spencer3ed469c2006-11-02 20:25:50 +00001215 //const unsigned long SignalNaN = 0x7ff4UL;
Brian Gaeke8a702e82004-08-25 19:00:42 +00001216
1217 // We need to grab the first part of the FP #
Brian Gaeke8a702e82004-08-25 19:00:42 +00001218 char Buffer[100];
1219
Dale Johannesen43421b32007-09-06 18:13:44 +00001220 uint64_t ll = DoubleToBits(V);
Reid Spencer2bc320d2006-05-31 22:26:11 +00001221 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
Brian Gaeke8a702e82004-08-25 19:00:42 +00001222
1223 std::string Num(&Buffer[0], &Buffer[6]);
1224 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1225
Owen Anderson1d0be152009-08-13 21:58:54 +00001226 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Brian Gaeke8a702e82004-08-25 19:00:42 +00001227 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1228 << Buffer << "\") /*nan*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001229 else
Brian Gaeke8a702e82004-08-25 19:00:42 +00001230 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1231 << Buffer << "\") /*nan*/ ";
Dale Johannesen43421b32007-09-06 18:13:44 +00001232 } else if (IsInf(V)) {
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001233 // The value is Inf
Dale Johannesen43421b32007-09-06 18:13:44 +00001234 if (V < 0) Out << '-';
Owen Anderson1d0be152009-08-13 21:58:54 +00001235 Out << "LLVM_INF" <<
1236 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Brian Gaeke8a702e82004-08-25 19:00:42 +00001237 << " /*inf*/ ";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001238 } else {
Brian Gaeke07b52b32004-08-25 19:37:26 +00001239 std::string Num;
Reid Spencerbcf81242006-11-05 19:26:37 +00001240#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
Brian Gaeke07b52b32004-08-25 19:37:26 +00001241 // Print out the constant as a floating point number.
1242 char Buffer[100];
Dale Johannesen43421b32007-09-06 18:13:44 +00001243 sprintf(Buffer, "%a", V);
Brian Gaeke07b52b32004-08-25 19:37:26 +00001244 Num = Buffer;
1245#else
Dale Johannesen43421b32007-09-06 18:13:44 +00001246 Num = ftostr(FPC->getValueAPF());
Brian Gaeke07b52b32004-08-25 19:37:26 +00001247#endif
Dale Johannesen43421b32007-09-06 18:13:44 +00001248 Out << Num;
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001249 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001250 }
1251 break;
1252 }
Chris Lattner6d492922002-08-19 21:32:41 +00001253
1254 case Type::ArrayTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001255 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001256 if (!Static) {
1257 Out << "(";
1258 printType(Out, CPV->getType());
1259 Out << ")";
1260 }
Dan Gohman193c2352008-06-02 21:30:49 +00001261 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner939732a2008-03-02 05:46:57 +00001262 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001263 printConstantArray(CA, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001264 } else {
1265 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001266 const ArrayType *AT = cast<ArrayType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001267 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001268 if (AT->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001269 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001270 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001271 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001272 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1273 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001274 printConstant(CZ, Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001275 }
1276 }
1277 Out << " }";
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001278 }
Dan Gohman193c2352008-06-02 21:30:49 +00001279 Out << " }"; // Arrays are wrapped in struct types.
Chris Lattner6d492922002-08-19 21:32:41 +00001280 break;
1281
Reid Spencer9d6565a2007-02-15 02:26:10 +00001282 case Type::VectorTyID:
Chris Lattner85feab62008-03-02 03:29:50 +00001283 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001284 if (!Static) {
1285 Out << "(";
1286 printType(Out, CPV->getType());
1287 Out << ")";
1288 }
Chris Lattner939732a2008-03-02 05:46:57 +00001289 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001290 printConstantVector(CV, Static);
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001291 } else {
1292 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1293 const VectorType *VT = cast<VectorType>(CPV->getType());
1294 Out << "{ ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001295 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohman9f8d5712008-07-24 17:57:48 +00001296 printConstant(CZ, Static);
Chris Lattner0a3d4d92008-03-02 03:18:46 +00001297 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattnerc8b6d332008-03-02 03:16:38 +00001298 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001299 printConstant(CZ, Static);
Robert Bocchinob78e8382006-01-20 20:43:57 +00001300 }
1301 Out << " }";
Robert Bocchinob78e8382006-01-20 20:43:57 +00001302 }
1303 break;
1304
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001305 case Type::StructTyID:
Dan Gohman1a245392008-07-23 18:41:03 +00001306 // Use C99 compound expression literal initializer syntax.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001307 if (!Static) {
1308 Out << "(";
1309 printType(Out, CPV->getType());
1310 Out << ")";
1311 }
Chris Lattnera9d12c02004-10-16 18:12:13 +00001312 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001313 const StructType *ST = cast<StructType>(CPV->getType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001314 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001315 if (ST->getNumElements()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001316 Out << ' ';
Owen Andersona7235ea2009-07-31 20:28:14 +00001317 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001318 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1319 Out << ", ";
Owen Andersona7235ea2009-07-31 20:28:14 +00001320 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001321 }
Chris Lattner6d492922002-08-19 21:32:41 +00001322 }
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001323 Out << " }";
1324 } else {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001325 Out << '{';
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001326 if (CPV->getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001327 Out << ' ';
Dan Gohman9f8d5712008-07-24 17:57:48 +00001328 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001329 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1330 Out << ", ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001331 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Chris Lattnercfb0fd22004-02-15 05:54:27 +00001332 }
1333 }
1334 Out << " }";
Chris Lattner6d492922002-08-19 21:32:41 +00001335 }
Chris Lattner6d492922002-08-19 21:32:41 +00001336 break;
Chris Lattner6d492922002-08-19 21:32:41 +00001337
1338 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001339 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +00001340 Out << "((";
Reid Spencere4d87aa2006-12-23 06:05:41 +00001341 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnercf135cb2003-06-02 03:10:53 +00001342 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +00001343 break;
Reid Spencer518310c2004-07-18 00:44:37 +00001344 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00001345 writeOperand(GV, Static);
Chris Lattner6d492922002-08-19 21:32:41 +00001346 break;
1347 }
1348 // FALL THROUGH
1349 default:
Torok Edwindac237e2009-07-08 20:53:28 +00001350#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001351 errs() << "Unknown constant type: " << *CPV << "\n";
Torok Edwindac237e2009-07-08 20:53:28 +00001352#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001353 llvm_unreachable(0);
Chris Lattner6d492922002-08-19 21:32:41 +00001354 }
1355}
1356
Reid Spencer1628cec2006-10-26 06:15:43 +00001357// Some constant expressions need to be casted back to the original types
1358// because their operands were casted to the expected type. This function takes
1359// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohman9f8d5712008-07-24 17:57:48 +00001360bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001361 bool NeedsExplicitCast = false;
Reid Spencer3da59db2006-11-27 01:05:10 +00001362 const Type *Ty = CE->getOperand(0)->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001363 bool TypeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001364 switch (CE->getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001365 case Instruction::Add:
1366 case Instruction::Sub:
1367 case Instruction::Mul:
1368 // We need to cast integer arithmetic so that it is always performed
1369 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001370 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001371 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001372 case Instruction::UDiv: NeedsExplicitCast = true; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001373 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001374 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001375 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
Reid Spencer3da59db2006-11-27 01:05:10 +00001376 case Instruction::SExt:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001377 Ty = CE->getType();
1378 NeedsExplicitCast = true;
1379 TypeIsSigned = true;
1380 break;
1381 case Instruction::ZExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00001382 case Instruction::Trunc:
1383 case Instruction::FPTrunc:
1384 case Instruction::FPExt:
1385 case Instruction::UIToFP:
1386 case Instruction::SIToFP:
1387 case Instruction::FPToUI:
1388 case Instruction::FPToSI:
1389 case Instruction::PtrToInt:
1390 case Instruction::IntToPtr:
1391 case Instruction::BitCast:
1392 Ty = CE->getType();
1393 NeedsExplicitCast = true;
1394 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001395 default: break;
1396 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001397 if (NeedsExplicitCast) {
Reid Spencer1628cec2006-10-26 06:15:43 +00001398 Out << "((";
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001399 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001400 printSimpleType(Out, Ty, TypeIsSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001401 else
Reid Spencer251f2142007-01-09 17:09:09 +00001402 printType(Out, Ty); // not integer, sign doesn't matter
Reid Spencer1628cec2006-10-26 06:15:43 +00001403 Out << ")(";
1404 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001405 return NeedsExplicitCast;
Reid Spencer1628cec2006-10-26 06:15:43 +00001406}
1407
1408// Print a constant assuming that it is the operand for a given Opcode. The
1409// opcodes that care about sign need to cast their operands to the expected
1410// type before the operation proceeds. This function does the casting.
1411void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1412
1413 // Extract the operand's type, we'll need it.
1414 const Type* OpTy = CPV->getType();
1415
1416 // Indicate whether to do the cast or not.
1417 bool shouldCast = false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001418 bool typeIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001419
1420 // Based on the Opcode for which this Constant is being written, determine
1421 // the new type to which the operand should be casted by setting the value
Reid Spencer3da59db2006-11-27 01:05:10 +00001422 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1423 // casted below.
Reid Spencer1628cec2006-10-26 06:15:43 +00001424 switch (Opcode) {
1425 default:
1426 // for most instructions, it doesn't matter
1427 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001428 case Instruction::Add:
1429 case Instruction::Sub:
1430 case Instruction::Mul:
1431 // We need to cast integer arithmetic so that it is always performed
1432 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001433 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001434 case Instruction::UDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001435 case Instruction::URem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001436 shouldCast = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001437 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001438 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001439 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +00001440 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001441 shouldCast = true;
1442 typeIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001443 break;
1444 }
1445
Reid Spencer3da59db2006-11-27 01:05:10 +00001446 // Write out the casted constant if we should, otherwise just write the
Reid Spencer1628cec2006-10-26 06:15:43 +00001447 // operand.
1448 if (shouldCast) {
1449 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001450 printSimpleType(Out, OpTy, typeIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001451 Out << ")";
Dan Gohman9f8d5712008-07-24 17:57:48 +00001452 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001453 Out << ")";
1454 } else
Dan Gohman9f8d5712008-07-24 17:57:48 +00001455 printConstant(CPV, false);
Reid Spencer1628cec2006-10-26 06:15:43 +00001456}
1457
Bill Wendling145aad02007-02-23 22:45:08 +00001458std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001459 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattner471f1e92010-01-13 19:54:07 +00001460 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1461 SmallString<128> Str;
1462 Mang->getNameWithPrefix(Str, GV, false);
Chris Lattner7481ae62010-01-22 18:33:00 +00001463 return CBEMangle(Str.str().str());
Chris Lattner471f1e92010-01-13 19:54:07 +00001464 }
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001465
1466 std::string Name = Operand->getName();
1467
1468 if (Name.empty()) { // Assign unique names to local temporaries.
1469 unsigned &No = AnonValueNumbers[Operand];
1470 if (No == 0)
1471 No = ++NextAnonValueNumber;
1472 Name = "tmp__" + utostr(No);
1473 }
1474
1475 std::string VarName;
1476 VarName.reserve(Name.capacity());
Bill Wendling145aad02007-02-23 22:45:08 +00001477
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001478 for (std::string::iterator I = Name.begin(), E = Name.end();
1479 I != E; ++I) {
1480 char ch = *I;
Bill Wendling145aad02007-02-23 22:45:08 +00001481
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001482 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1483 (ch >= '0' && ch <= '9') || ch == '_')) {
1484 char buffer[5];
1485 sprintf(buffer, "_%x_", ch);
1486 VarName += buffer;
1487 } else
1488 VarName += ch;
Bill Wendling145aad02007-02-23 22:45:08 +00001489 }
1490
Chris Lattnerca1bafd2009-07-13 23:46:46 +00001491 return "llvm_cbe_" + VarName;
Bill Wendling145aad02007-02-23 22:45:08 +00001492}
1493
Chris Lattnere56d9462008-05-31 09:23:55 +00001494/// writeInstComputationInline - Emit the computation for the specified
1495/// instruction inline, with no destination provided.
1496void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen06398942009-06-18 01:07:23 +00001497 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1498 // Validate this.
1499 const Type *Ty = I.getType();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001500 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001501 Ty!=Type::getInt8Ty(I.getContext()) &&
1502 Ty!=Type::getInt16Ty(I.getContext()) &&
1503 Ty!=Type::getInt32Ty(I.getContext()) &&
1504 Ty!=Type::getInt64Ty(I.getContext()))) {
Torok Edwindac237e2009-07-08 20:53:28 +00001505 llvm_report_error("The C backend does not currently support integer "
1506 "types of widths other than 1, 8, 16, 32, 64.\n"
1507 "This is being tracked as PR 4158.");
Dale Johannesen06398942009-06-18 01:07:23 +00001508 }
1509
Chris Lattnere56d9462008-05-31 09:23:55 +00001510 // If this is a non-trivial bool computation, make sure to truncate down to
1511 // a 1 bit value. This is important because we want "add i1 x, y" to return
1512 // "0" when x and y are true, not "2" for example.
1513 bool NeedBoolTrunc = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00001514 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1515 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnere56d9462008-05-31 09:23:55 +00001516 NeedBoolTrunc = true;
1517
1518 if (NeedBoolTrunc)
1519 Out << "((";
1520
1521 visit(I);
1522
1523 if (NeedBoolTrunc)
1524 Out << ")&1)";
1525}
1526
1527
Dan Gohman9f8d5712008-07-24 17:57:48 +00001528void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001529 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnere56d9462008-05-31 09:23:55 +00001530 // Should we inline this instruction to build a tree?
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001531 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001532 Out << '(';
Chris Lattnere56d9462008-05-31 09:23:55 +00001533 writeInstComputationInline(*I);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001534 Out << ')';
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001535 return;
1536 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00001537
Reid Spencer518310c2004-07-18 00:44:37 +00001538 Constant* CPV = dyn_cast<Constant>(Operand);
Bill Wendling145aad02007-02-23 22:45:08 +00001539
1540 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohman9f8d5712008-07-24 17:57:48 +00001541 printConstant(CPV, Static);
Bill Wendling145aad02007-02-23 22:45:08 +00001542 else
1543 Out << GetValueName(Operand);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001544}
1545
Dan Gohman9f8d5712008-07-24 17:57:48 +00001546void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00001547 bool isAddressImplicit = isAddressExposed(Operand);
1548 if (isAddressImplicit)
Reid Spencer3da59db2006-11-27 01:05:10 +00001549 Out << "(&"; // Global variables are referenced as their addresses by llvm
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001550
Dan Gohman9f8d5712008-07-24 17:57:48 +00001551 writeOperandInternal(Operand, Static);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001552
Chris Lattnere05252b42008-03-02 08:07:24 +00001553 if (isAddressImplicit)
Misha Brukmanb70aaa62005-02-14 18:52:35 +00001554 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001555}
1556
Reid Spencer1628cec2006-10-26 06:15:43 +00001557// Some instructions need to have their result value casted back to the
1558// original types because their operands were casted to the expected type.
1559// This function takes care of detecting that case and printing the cast
1560// for the Instruction.
1561bool CWriter::writeInstructionCast(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001562 const Type *Ty = I.getOperand(0)->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00001563 switch (I.getOpcode()) {
Dan Gohman5a11aba2008-07-18 18:43:12 +00001564 case Instruction::Add:
1565 case Instruction::Sub:
1566 case Instruction::Mul:
1567 // We need to cast integer arithmetic so that it is always performed
1568 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001569 case Instruction::LShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001570 case Instruction::URem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001571 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001572 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001573 printSimpleType(Out, Ty, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001574 Out << ")(";
1575 return true;
Reid Spencer3822ff52006-11-08 06:47:33 +00001576 case Instruction::AShr:
Reid Spencer0a783f72006-11-02 01:53:59 +00001577 case Instruction::SRem:
Reid Spencer3da59db2006-11-27 01:05:10 +00001578 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001579 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001580 printSimpleType(Out, Ty, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001581 Out << ")(";
1582 return true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001583 default: break;
1584 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001585 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001586}
1587
1588// Write the operand with a cast to another type based on the Opcode being used.
1589// This will be used in cases where an instruction has specific type
1590// requirements (usually signedness) for its operands.
1591void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1592
1593 // Extract the operand's type, we'll need it.
1594 const Type* OpTy = Operand->getType();
1595
1596 // Indicate whether to do the cast or not.
1597 bool shouldCast = false;
1598
Reid Spencere4d87aa2006-12-23 06:05:41 +00001599 // Indicate whether the cast should be to a signed type or not.
1600 bool castIsSigned = false;
1601
Reid Spencer1628cec2006-10-26 06:15:43 +00001602 // Based on the Opcode for which this Operand is being written, determine
1603 // the new type to which the operand should be casted by setting the value
1604 // of OpTy. If we change OpTy, also set shouldCast to true.
1605 switch (Opcode) {
1606 default:
1607 // for most instructions, it doesn't matter
1608 break;
Dan Gohman5a11aba2008-07-18 18:43:12 +00001609 case Instruction::Add:
1610 case Instruction::Sub:
1611 case Instruction::Mul:
1612 // We need to cast integer arithmetic so that it is always performed
1613 // as unsigned, to avoid undefined behavior on overflow.
Reid Spencer3822ff52006-11-08 06:47:33 +00001614 case Instruction::LShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001615 case Instruction::UDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001616 case Instruction::URem: // Cast to unsigned first
1617 shouldCast = true;
1618 castIsSigned = false;
Reid Spencer1628cec2006-10-26 06:15:43 +00001619 break;
Chris Lattner96b207c2007-09-22 20:16:48 +00001620 case Instruction::GetElementPtr:
Reid Spencer3822ff52006-11-08 06:47:33 +00001621 case Instruction::AShr:
Reid Spencer1628cec2006-10-26 06:15:43 +00001622 case Instruction::SDiv:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001623 case Instruction::SRem: // Cast to signed first
1624 shouldCast = true;
1625 castIsSigned = true;
Reid Spencer1628cec2006-10-26 06:15:43 +00001626 break;
1627 }
1628
1629 // Write out the casted operand if we should, otherwise just write the
1630 // operand.
1631 if (shouldCast) {
1632 Out << "((";
Reid Spencera54b7cb2007-01-12 07:05:14 +00001633 printSimpleType(Out, OpTy, castIsSigned);
Reid Spencer1628cec2006-10-26 06:15:43 +00001634 Out << ")";
Chris Lattner72623362007-05-03 02:57:13 +00001635 writeOperand(Operand);
Reid Spencer1628cec2006-10-26 06:15:43 +00001636 Out << ")";
1637 } else
1638 writeOperand(Operand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001639}
Reid Spencer1628cec2006-10-26 06:15:43 +00001640
Reid Spencere4d87aa2006-12-23 06:05:41 +00001641// Write the operand with a cast to another type based on the icmp predicate
1642// being used.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001643void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1644 // This has to do a cast to ensure the operand has the right signedness.
1645 // Also, if the operand is a pointer, we make sure to cast to an integer when
1646 // doing the comparison both for signedness and so that the C compiler doesn't
1647 // optimize things like "p < NULL" to false (p may contain an integer value
1648 // f.e.).
1649 bool shouldCast = Cmp.isRelational();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001650
1651 // Write out the casted operand if we should, otherwise just write the
1652 // operand.
Chris Lattner5bda9e42007-09-15 06:51:03 +00001653 if (!shouldCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001654 writeOperand(Operand);
Chris Lattner5bda9e42007-09-15 06:51:03 +00001655 return;
1656 }
1657
1658 // Should this be a signed comparison? If so, convert to signed.
Nick Lewycky4a134af2009-10-25 05:20:17 +00001659 bool castIsSigned = Cmp.isSigned();
Chris Lattner5bda9e42007-09-15 06:51:03 +00001660
1661 // If the operand was a pointer, convert to a large integer type.
1662 const Type* OpTy = Operand->getType();
1663 if (isa<PointerType>(OpTy))
Owen Anderson1d0be152009-08-13 21:58:54 +00001664 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner5bda9e42007-09-15 06:51:03 +00001665
1666 Out << "((";
1667 printSimpleType(Out, OpTy, castIsSigned);
1668 Out << ")";
1669 writeOperand(Operand);
1670 Out << ")";
Reid Spencer1628cec2006-10-26 06:15:43 +00001671}
1672
Chris Lattner41488192003-06-28 17:15:12 +00001673// generateCompilerSpecificCode - This is where we add conditional compilation
1674// directives to cater to specific compilers as need be.
1675//
David Greene71847812009-07-14 20:18:05 +00001676static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman271515a2008-04-02 23:52:49 +00001677 const TargetData *TD) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00001678 // Alloca is hard to get, and we don't want to include stdlib.h here.
Chris Lattner41488192003-06-28 17:15:12 +00001679 Out << "/* get a declaration for alloca */\n"
Chris Lattnerd9477602006-06-02 18:54:01 +00001680 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
Anton Korobeynikov57fc00d2007-04-17 09:20:00 +00001681 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001682 << "#define _alloca(x) __builtin_alloca((x))\n"
Reid Spencera8411a62005-01-23 04:32:47 +00001683 << "#elif defined(__APPLE__)\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001684 << "extern void *__builtin_alloca(unsigned long);\n"
1685 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00001686 << "#define longjmp _longjmp\n"
1687 << "#define setjmp _setjmp\n"
Brian Gaekece630052004-12-10 05:44:45 +00001688 << "#elif defined(__sun__)\n"
1689 << "#if defined(__sparcv9)\n"
1690 << "extern void *__builtin_alloca(unsigned long);\n"
1691 << "#else\n"
1692 << "extern void *__builtin_alloca(unsigned int);\n"
1693 << "#endif\n"
1694 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikove392c832009-08-05 09:31:07 +00001695 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Chris Lattner60e66742004-10-06 04:21:52 +00001696 << "#define alloca(x) __builtin_alloca(x)\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001697 << "#elif defined(_MSC_VER)\n"
Jeff Cohene2cd2a02007-03-29 17:42:21 +00001698 << "#define inline _inline\n"
Jeff Cohenab478952007-03-28 23:08:37 +00001699 << "#define alloca(x) _alloca(x)\n"
1700 << "#else\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001701 << "#include <alloca.h>\n"
1702 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +00001703
1704 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1705 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +00001706 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +00001707 << "#define __attribute__(X)\n"
Brian Gaeke27f7a712003-12-11 00:24:36 +00001708 << "#endif\n\n";
1709
Brian Gaeke27f7a712003-12-11 00:24:36 +00001710 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1711 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1712 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1713 << "#elif defined(__GNUC__)\n"
1714 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1715 << "#else\n"
1716 << "#define __EXTERNAL_WEAK__\n"
1717 << "#endif\n\n";
Brian Gaeke27f7a712003-12-11 00:24:36 +00001718
1719 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1720 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1721 << "#define __ATTRIBUTE_WEAK__\n"
1722 << "#elif defined(__GNUC__)\n"
1723 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1724 << "#else\n"
1725 << "#define __ATTRIBUTE_WEAK__\n"
1726 << "#endif\n\n";
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001727
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001728 // Add hidden visibility support. FIXME: APPLE_CC?
1729 Out << "#if defined(__GNUC__)\n"
1730 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1731 << "#endif\n\n";
1732
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001733 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1734 // From the GCC documentation:
Misha Brukmand6a29a52005-04-20 16:05:03 +00001735 //
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001736 // double __builtin_nan (const char *str)
1737 //
1738 // This is an implementation of the ISO C99 function nan.
1739 //
1740 // Since ISO C99 defines this function in terms of strtod, which we do
1741 // not implement, a description of the parsing is in order. The string is
1742 // parsed as by strtol; that is, the base is recognized by leading 0 or
1743 // 0x prefixes. The number parsed is placed in the significand such that
1744 // the least significant bit of the number is at the least significant
1745 // bit of the significand. The number is truncated to fit the significand
1746 // field provided. The significand is forced to be a quiet NaN.
1747 //
1748 // This function, if given a string literal, is evaluated early enough
1749 // that it is considered a compile-time constant.
1750 //
1751 // float __builtin_nanf (const char *str)
1752 //
1753 // Similar to __builtin_nan, except the return type is float.
1754 //
1755 // double __builtin_inf (void)
1756 //
1757 // Similar to __builtin_huge_val, except a warning is generated if the
1758 // target floating-point format does not support infinities. This
1759 // function is suitable for implementing the ISO C99 macro INFINITY.
1760 //
1761 // float __builtin_inff (void)
1762 //
1763 // Similar to __builtin_inf, except the return type is float.
1764 Out << "#ifdef __GNUC__\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001765 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1766 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1767 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1768 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1769 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1770 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
Chris Lattnerf9a05322006-02-13 22:22:42 +00001771 << "#define LLVM_PREFETCH(addr,rw,locality) "
1772 "__builtin_prefetch(addr,rw,locality)\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001773 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1774 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001775 << "#define LLVM_ASM __asm__\n"
Brian Gaeke043c0bb2004-07-21 03:15:26 +00001776 << "#else\n"
Brian Gaeke8a702e82004-08-25 19:00:42 +00001777 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1778 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1779 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1780 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1781 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1782 << "#define LLVM_INFF 0.0F /* Float */\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001783 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
Chris Lattner9a571ba2006-03-07 22:58:23 +00001784 << "#define __ATTRIBUTE_CTOR__\n"
1785 << "#define __ATTRIBUTE_DTOR__\n"
Chris Lattnerdacbe7b2006-07-28 20:58:47 +00001786 << "#define LLVM_ASM(X)\n"
Chris Lattner50a8a172005-05-06 06:58:42 +00001787 << "#endif\n\n";
Chris Lattner40c1b662007-05-13 22:19:27 +00001788
1789 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1790 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1791 << "#define __builtin_stack_restore(X) /* noop */\n"
1792 << "#endif\n\n";
Chris Lattner50a8a172005-05-06 06:58:42 +00001793
Dan Gohman271515a2008-04-02 23:52:49 +00001794 // Output typedefs for 128-bit integers. If these are needed with a
1795 // 32-bit target or with a C compiler that doesn't support mode(TI),
1796 // more drastic measures will be needed.
Chris Lattner9e4ff942008-06-16 04:25:29 +00001797 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1798 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1799 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1800 << "#endif\n\n";
Dan Gohmand7614802008-04-02 19:40:14 +00001801
Chris Lattner50a8a172005-05-06 06:58:42 +00001802 // Output target-specific code that should be inserted into main.
1803 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001804}
1805
Chris Lattner9a571ba2006-03-07 22:58:23 +00001806/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1807/// the StaticTors set.
1808static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1809 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1810 if (!InitList) return;
1811
1812 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1813 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1814 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1815
1816 if (CS->getOperand(1)->isNullValue())
1817 return; // Found a null terminator, exit printing.
1818 Constant *FP = CS->getOperand(1);
1819 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +00001820 if (CE->isCast())
Chris Lattner9a571ba2006-03-07 22:58:23 +00001821 FP = CE->getOperand(0);
1822 if (Function *F = dyn_cast<Function>(FP))
1823 StaticTors.insert(F);
1824 }
1825}
1826
1827enum SpecialGlobalClass {
1828 NotSpecial = 0,
1829 GlobalCtors, GlobalDtors,
1830 NotPrinted
1831};
1832
1833/// getGlobalVariableClass - If this is a global that is specially recognized
1834/// by LLVM, return a code that indicates how we should handle it.
1835static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1836 // If this is a global ctors/dtors list, handle it now.
1837 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1838 if (GV->getName() == "llvm.global_ctors")
1839 return GlobalCtors;
1840 else if (GV->getName() == "llvm.global_dtors")
1841 return GlobalDtors;
1842 }
1843
Dan Gohmanf451cb82010-02-10 16:03:48 +00001844 // Otherwise, if it is other metadata, don't print it. This catches things
Chris Lattner9a571ba2006-03-07 22:58:23 +00001845 // like debug information.
1846 if (GV->getSection() == "llvm.metadata")
1847 return NotPrinted;
1848
1849 return NotSpecial;
1850}
1851
Anton Korobeynikove641b522009-08-05 09:29:56 +00001852// PrintEscapedString - Print each character of the specified string, escaping
1853// it if it is not printable or if it is an escape char.
1854static void PrintEscapedString(const char *Str, unsigned Length,
1855 raw_ostream &Out) {
1856 for (unsigned i = 0; i != Length; ++i) {
1857 unsigned char C = Str[i];
1858 if (isprint(C) && C != '\\' && C != '"')
1859 Out << C;
1860 else if (C == '\\')
1861 Out << "\\\\";
1862 else if (C == '\"')
1863 Out << "\\\"";
1864 else if (C == '\t')
1865 Out << "\\t";
1866 else
1867 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1868 }
1869}
1870
1871// PrintEscapedString - Print each character of the specified string, escaping
1872// it if it is not printable or if it is an escape char.
1873static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1874 PrintEscapedString(Str.c_str(), Str.size(), Out);
1875}
Chris Lattner9a571ba2006-03-07 22:58:23 +00001876
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001877bool CWriter::doInitialization(Module &M) {
Daniel Dunbar53448652009-07-17 03:43:21 +00001878 FunctionPass::doInitialization(M);
1879
Chris Lattner94f4f8e2004-02-13 23:00:29 +00001880 // Initialize
1881 TheModule = &M;
Chris Lattnerc2421432004-05-09 04:30:20 +00001882
Reid Spencer519e2392007-01-29 17:51:02 +00001883 TD = new TargetData(&M);
1884 IL = new IntrinsicLowering(*TD);
1885 IL->AddPrototypes(M);
Misha Brukmand6a29a52005-04-20 16:05:03 +00001886
Chris Lattnerc0dba722010-01-17 18:22:35 +00001887#if 0
1888 std::string Triple = TheModule->getTargetTriple();
1889 if (Triple.empty())
1890 Triple = llvm::sys::getHostTriple();
1891
1892 std::string E;
1893 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1894 TAsm = Match->createAsmInfo(Triple);
1895#endif
Chris Lattner8eeba352010-01-20 06:34:14 +00001896 TAsm = new CBEMCAsmInfo();
Chris Lattnerc0dba722010-01-17 18:22:35 +00001897 Mang = new Mangler(*TAsm);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001898
Chris Lattner9a571ba2006-03-07 22:58:23 +00001899 // Keep track of which functions are static ctors/dtors so they can have
1900 // an attribute added to their prototypes.
1901 std::set<Function*> StaticCtors, StaticDtors;
1902 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1903 I != E; ++I) {
1904 switch (getGlobalVariableClass(I)) {
1905 default: break;
1906 case GlobalCtors:
1907 FindStaticTors(I, StaticCtors);
1908 break;
1909 case GlobalDtors:
1910 FindStaticTors(I, StaticDtors);
1911 break;
1912 }
1913 }
1914
Chris Lattner16c7bb22002-05-09 02:28:59 +00001915 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +00001916 Out << "/* Provide Declarations */\n";
Chris Lattnerc59c1182003-11-16 22:06:14 +00001917 Out << "#include <stdarg.h>\n"; // Varargs support
1918 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman271515a2008-04-02 23:52:49 +00001919 generateCompilerSpecificCode(Out, TD);
Chris Lattnerc59c1182003-11-16 22:06:14 +00001920
Chris Lattnercf135cb2003-06-02 03:10:53 +00001921 // Provide a definition for `bool' if not compiling with a C++ compiler.
1922 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +00001923 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Misha Brukmand6a29a52005-04-20 16:05:03 +00001924
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00001925 << "\n\n/* Support for floating point constants */\n"
1926 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +00001927 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001928 << "typedef struct { unsigned long long f1; unsigned short f2; "
1929 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen6e644732007-10-15 01:05:37 +00001930 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001931 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1932 " ConstantFP128Ty;\n"
Chris Lattnera4d4a852002-08-19 21:48:40 +00001933 << "\n\n/* Global Declarations */\n";
1934
1935 // First output all the declarations for the program, because C requires
1936 // Functions & globals to be declared before they are used.
1937 //
Anton Korobeynikove641b522009-08-05 09:29:56 +00001938 if (!M.getModuleInlineAsm().empty()) {
1939 Out << "/* Module asm statements */\n"
1940 << "asm(";
1941
1942 // Split the string into lines, to make it easier to read the .ll file.
1943 std::string Asm = M.getModuleInlineAsm();
1944 size_t CurPos = 0;
1945 size_t NewLine = Asm.find_first_of('\n', CurPos);
1946 while (NewLine != std::string::npos) {
1947 // We found a newline, print the portion of the asm string from the
1948 // last newline up to this newline.
1949 Out << "\"";
1950 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1951 Out);
1952 Out << "\\n\"\n";
1953 CurPos = NewLine+1;
1954 NewLine = Asm.find_first_of('\n', CurPos);
1955 }
1956 Out << "\"";
1957 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1958 Out << "\");\n"
1959 << "/* End Module asm statements */\n";
1960 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001961
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001962 // Loop over the symbol table, emitting all named constants...
Reid Spencer78d033e2007-01-06 07:24:44 +00001963 printModuleTypes(M.getTypeSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001964
Chris Lattnera4d4a852002-08-19 21:48:40 +00001965 // Global variable declarations...
Chris Lattnere4d5c442005-03-15 04:54:21 +00001966 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001967 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00001968 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1969 I != E; ++I) {
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001970
Dale Johannesenaafce772008-05-14 20:12:51 +00001971 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1972 I->hasCommonLinkage())
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00001973 Out << "extern ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001974 else if (I->hasDLLImportLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001975 Out << "__declspec(dllimport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00001976 else
1977 continue; // Internal Global
1978
1979 // Thread Local Storage
1980 if (I->isThreadLocal())
1981 Out << "__thread ";
1982
1983 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1984
1985 if (I->hasExternalWeakLinkage())
1986 Out << " __EXTERNAL_WEAK__";
1987 Out << ";\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001988 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +00001989 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001990
Chris Lattnera4d4a852002-08-19 21:48:40 +00001991 // Function declarations
Chris Lattner9a571ba2006-03-07 22:58:23 +00001992 Out << "\n/* Function Declarations */\n";
Chris Lattner57da2522005-08-23 20:22:50 +00001993 Out << "double fmod(double, double);\n"; // Support for FP rem
1994 Out << "float fmodf(float, float);\n";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00001995 Out << "long double fmodl(long double, long double);\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00001996
Chris Lattner9a571ba2006-03-07 22:58:23 +00001997 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1998 // Don't print declarations for intrinsic functions.
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001999 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Reid Spencer2cb46e12006-10-22 09:58:21 +00002000 I->getName() != "longjmp" && I->getName() != "_setjmp") {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00002001 if (I->hasExternalWeakLinkage())
2002 Out << "extern ";
Chris Lattner9a571ba2006-03-07 22:58:23 +00002003 printFunctionSignature(I, true);
Evan Cheng3e3aa862008-06-07 07:50:29 +00002004 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattner9a571ba2006-03-07 22:58:23 +00002005 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00002006 if (I->hasExternalWeakLinkage())
2007 Out << " __EXTERNAL_WEAK__";
Chris Lattner9a571ba2006-03-07 22:58:23 +00002008 if (StaticCtors.count(I))
2009 Out << " __ATTRIBUTE_CTOR__";
2010 if (StaticDtors.count(I))
2011 Out << " __ATTRIBUTE_DTOR__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002012 if (I->hasHiddenVisibility())
2013 Out << " __HIDDEN__";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002014
2015 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar8f603022009-07-22 21:10:12 +00002016 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002017
Chris Lattner9a571ba2006-03-07 22:58:23 +00002018 Out << ";\n";
Chris Lattner4cda8352002-08-20 16:55:48 +00002019 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002020 }
2021
Joel Stanley54f60322003-06-25 04:52:09 +00002022 // Output the global variable declarations
Chris Lattnere4d5c442005-03-15 04:54:21 +00002023 if (!M.global_empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +00002024 Out << "\n\n/* Global Variable Declarations */\n";
Chris Lattnerf9a05322006-02-13 22:22:42 +00002025 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2026 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002027 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002028 // Ignore special globals, such as debug info.
2029 if (getGlobalVariableClass(I))
2030 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002031
Rafael Espindolabb46f522009-01-15 20:18:42 +00002032 if (I->hasLocalLinkage())
Chris Lattnercc16a8e2004-12-03 17:19:10 +00002033 Out << "static ";
2034 else
2035 Out << "extern ";
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 Lattner2580d4f2003-11-03 17:32:38 +00002043
2044 if (I->hasLinkOnceLinkage())
2045 Out << " __attribute__((common))";
Dale Johannesenaafce772008-05-14 20:12:51 +00002046 else if (I->hasCommonLinkage()) // FIXME is this right?
2047 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner2580d4f2003-11-03 17:32:38 +00002048 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002049 Out << " __ATTRIBUTE_WEAK__";
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00002050 else if (I->hasExternalWeakLinkage())
2051 Out << " __EXTERNAL_WEAK__";
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002052 if (I->hasHiddenVisibility())
2053 Out << " __HIDDEN__";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +00002054 Out << ";\n";
2055 }
2056 }
2057
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002058 // Output the global variable definitions and contents...
Chris Lattnere4d5c442005-03-15 04:54:21 +00002059 if (!M.global_empty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +00002060 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Cheng3e3aa862008-06-07 07:50:29 +00002061 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Chris Lattnerf9a05322006-02-13 22:22:42 +00002062 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +00002063 if (!I->isDeclaration()) {
Chris Lattner9a571ba2006-03-07 22:58:23 +00002064 // Ignore special globals, such as debug info.
2065 if (getGlobalVariableClass(I))
2066 continue;
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002067
Rafael Espindolabb46f522009-01-15 20:18:42 +00002068 if (I->hasLocalLinkage())
Chris Lattnere8e035b2002-10-16 20:08:47 +00002069 Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002070 else if (I->hasDLLImportLinkage())
2071 Out << "__declspec(dllimport) ";
2072 else if (I->hasDLLExportLinkage())
2073 Out << "__declspec(dllexport) ";
Lauro Ramos Venancio26ca64c2007-04-12 18:42:08 +00002074
2075 // Thread Local Storage
2076 if (I->isThreadLocal())
2077 Out << "__thread ";
2078
Reid Spencer251f2142007-01-09 17:09:09 +00002079 printType(Out, I->getType()->getElementType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002080 GetValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +00002081 if (I->hasLinkOnceLinkage())
2082 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +00002083 else if (I->hasWeakLinkage())
Brian Gaeke27f7a712003-12-11 00:24:36 +00002084 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesenaafce772008-05-14 20:12:51 +00002085 else if (I->hasCommonLinkage())
2086 Out << " __ATTRIBUTE_WEAK__";
Chris Lattner5ea326a2003-11-03 17:35:00 +00002087
Anton Korobeynikov7f705592007-01-12 19:20:47 +00002088 if (I->hasHiddenVisibility())
2089 Out << " __HIDDEN__";
2090
Chris Lattner5ea326a2003-11-03 17:35:00 +00002091 // If the initializer is not null, emit the initializer. If it is null,
2092 // we try to avoid emitting large amounts of zeros. The problem with
2093 // this, however, occurs when the variable has weak linkage. In this
2094 // case, the assembler will complain about the variable being both weak
2095 // and common, so we disable this optimization.
Dale Johannesenaafce772008-05-14 20:12:51 +00002096 // FIXME common linkage should avoid this problem.
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002097 if (!I->getInitializer()->isNullValue()) {
Chris Lattner940b08d2003-06-06 07:10:24 +00002098 Out << " = " ;
Dan Gohman9f8d5712008-07-24 17:57:48 +00002099 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002100 } else if (I->hasWeakLinkage()) {
2101 // We have to specify an initializer, but it doesn't have to be
2102 // complete. If the value is an aggregate, print out { 0 }, and let
2103 // the compiler figure out the rest of the zeros.
2104 Out << " = " ;
2105 if (isa<StructType>(I->getInitializer()->getType()) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00002106 isa<VectorType>(I->getInitializer()->getType())) {
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002107 Out << "{ 0 }";
Dan Gohman193c2352008-06-02 21:30:49 +00002108 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2109 // As with structs and vectors, but with an extra set of braces
2110 // because arrays are wrapped in structs.
2111 Out << "{ { 0 } }";
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002112 } else {
2113 // Just print it out normally.
Dan Gohman9f8d5712008-07-24 17:57:48 +00002114 writeOperand(I->getInitializer(), true);
Chris Lattnerf358c5a2004-02-20 05:49:22 +00002115 }
Chris Lattner940b08d2003-06-06 07:10:24 +00002116 }
Chris Lattnere8e035b2002-10-16 20:08:47 +00002117 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +00002118 }
Chris Lattnera4d4a852002-08-19 21:48:40 +00002119 }
2120
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002121 if (!M.empty())
Chris Lattnera4d4a852002-08-19 21:48:40 +00002122 Out << "\n\n/* Function Bodies */\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002123
2124 // Emit some helper functions for dealing with FCMP instruction's
2125 // predicates
2126 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2127 Out << "return X == X && Y == Y; }\n";
2128 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2129 Out << "return X != X || Y != Y; }\n";
2130 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002131 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002132 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002133 Out << "return X != Y; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002134 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002135 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002136 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002137 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002138 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002139 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002140 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002141 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002142 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002143 Out << "return X == Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002144 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002145 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002146 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002147 Out << "return X < Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002148 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002149 Out << "return X > Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002150 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002151 Out << "return X <= Y ; }\n";
Reid Spencerb801a272007-01-08 06:58:32 +00002152 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
Reid Spencerfbe7ae92007-01-08 08:00:00 +00002153 Out << "return X >= Y ; }\n";
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002154 return false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002155}
2156
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002157
Chris Lattner9860e772003-10-12 04:36:29 +00002158/// Output all floating point constants that cannot be printed accurately...
Chris Lattner68758072004-05-09 06:20:51 +00002159void CWriter::printFloatingPointConstants(Function &F) {
Chris Lattner9860e772003-10-12 04:36:29 +00002160 // Scan the module for floating point constants. If any FP constant is used
2161 // in the function, we want to redirect it here so that we do not depend on
2162 // the precision of the printed form, unless the printed form preserves
2163 // precision.
2164 //
Chris Lattner68758072004-05-09 06:20:51 +00002165 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2166 I != E; ++I)
Chris Lattneraecc22a2008-10-22 04:53:16 +00002167 printFloatingPointConstants(*I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002168
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002169 Out << '\n';
Chris Lattner68758072004-05-09 06:20:51 +00002170}
Chris Lattner9860e772003-10-12 04:36:29 +00002171
Chris Lattneraecc22a2008-10-22 04:53:16 +00002172void CWriter::printFloatingPointConstants(const Constant *C) {
2173 // If this is a constant expression, recursively check for constant fp values.
2174 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2175 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2176 printFloatingPointConstants(CE->getOperand(i));
2177 return;
2178 }
2179
2180 // Otherwise, check for a FP constant that we need to print.
2181 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2182 if (FPC == 0 ||
2183 // Do not put in FPConstantMap if safe.
2184 isFPCSafeToPrint(FPC) ||
2185 // Already printed this constant?
2186 FPConstantMap.count(FPC))
2187 return;
2188
2189 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2190
Owen Anderson1d0be152009-08-13 21:58:54 +00002191 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002192 double Val = FPC->getValueAPF().convertToDouble();
2193 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2194 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2195 << " = 0x" << utohexstr(i)
2196 << "ULL; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002197 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002198 float Val = FPC->getValueAPF().convertToFloat();
2199 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2200 getZExtValue();
2201 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2202 << " = 0x" << utohexstr(i)
2203 << "U; /* " << Val << " */\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00002204 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002205 // api needed to prevent premature destruction
2206 APInt api = FPC->getValueAPF().bitcastToAPInt();
2207 const uint64_t *p = api.getRawData();
2208 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002209 << " = { 0x" << utohexstr(p[0])
2210 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattneraecc22a2008-10-22 04:53:16 +00002211 << "}; /* Long double constant */\n";
Anton Korobeynikovefc3f3a2009-08-26 17:39:23 +00002212 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2213 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattneraecc22a2008-10-22 04:53:16 +00002214 APInt api = FPC->getValueAPF().bitcastToAPInt();
2215 const uint64_t *p = api.getRawData();
2216 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2217 << " = { 0x"
2218 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2219 << "}; /* Long double constant */\n";
2220
2221 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002222 llvm_unreachable("Unknown float type!");
Chris Lattneraecc22a2008-10-22 04:53:16 +00002223 }
2224}
2225
2226
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002227
Chris Lattner2db41cd2002-09-20 15:12:13 +00002228/// printSymbolTable - Run through symbol table looking for type names. If a
Robert Bocchinob78e8382006-01-20 20:43:57 +00002229/// type name is found, emit its declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +00002230///
Reid Spencer78d033e2007-01-06 07:24:44 +00002231void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
Reid Spencer555a0b12006-12-11 20:39:15 +00002232 Out << "/* Helper union for bitcasts */\n";
2233 Out << "typedef union {\n";
Reid Spencer47857812006-12-31 05:55:36 +00002234 Out << " unsigned int Int32;\n";
2235 Out << " unsigned long long Int64;\n";
Reid Spencer22b36fb2006-12-12 00:11:08 +00002236 Out << " float Float;\n";
2237 Out << " double Double;\n";
Reid Spencer555a0b12006-12-11 20:39:15 +00002238 Out << "} llvmBitCastUnion;\n";
2239
Chris Lattnerb15fde22005-03-06 02:28:23 +00002240 // We are only interested in the type plane of the symbol table.
Reid Spencer78d033e2007-01-06 07:24:44 +00002241 TypeSymbolTable::const_iterator I = TST.begin();
2242 TypeSymbolTable::const_iterator End = TST.end();
Chris Lattnerb15fde22005-03-06 02:28:23 +00002243
2244 // If there are no type names, exit early.
2245 if (I == End) return;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002246
Chris Lattner58d04d42002-09-20 15:18:30 +00002247 // Print out forward declarations for structure types before anything else!
2248 Out << "/* Structure forward decls */\n";
Chris Lattnera80cc932007-01-16 18:02:45 +00002249 for (; I != End; ++I) {
Chris Lattner7481ae62010-01-22 18:33:00 +00002250 std::string Name = "struct " + CBEMangle("l_"+I->first);
Chris Lattner471f1e92010-01-13 19:54:07 +00002251 Out << Name << ";\n";
2252 TypeNames.insert(std::make_pair(I->second, Name));
Chris Lattnera80cc932007-01-16 18:02:45 +00002253 }
Chris Lattner58d04d42002-09-20 15:18:30 +00002254
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002255 Out << '\n';
Chris Lattner58d04d42002-09-20 15:18:30 +00002256
Chris Lattner19e8b0c2007-01-16 07:22:23 +00002257 // Now we can print out typedefs. Above, we guaranteed that this can only be
Chris Lattnera80cc932007-01-16 18:02:45 +00002258 // for struct or opaque types.
Chris Lattner58d04d42002-09-20 15:18:30 +00002259 Out << "/* Typedefs */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002260 for (I = TST.begin(); I != End; ++I) {
Chris Lattner7481ae62010-01-22 18:33:00 +00002261 std::string Name = CBEMangle("l_"+I->first);
Chris Lattner68758072004-05-09 06:20:51 +00002262 Out << "typedef ";
Chris Lattner471f1e92010-01-13 19:54:07 +00002263 printType(Out, I->second, false, Name);
Chris Lattner68758072004-05-09 06:20:51 +00002264 Out << ";\n";
2265 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002266
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002267 Out << '\n';
Chris Lattner3ef6dc72002-05-09 14:40:11 +00002268
Chris Lattner2c601a72002-09-20 15:05:40 +00002269 // Keep track of which structures have been printed so far...
Dan Gohman193c2352008-06-02 21:30:49 +00002270 std::set<const Type *> StructPrinted;
Chris Lattner2c601a72002-09-20 15:05:40 +00002271
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002272 // Loop over all structures then push them into the stack so they are
2273 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +00002274 //
Chris Lattner58d04d42002-09-20 15:18:30 +00002275 Out << "/* Structure contents */\n";
Reid Spencer78d033e2007-01-06 07:24:44 +00002276 for (I = TST.begin(); I != End; ++I)
Dan Gohman193c2352008-06-02 21:30:49 +00002277 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Chris Lattnerfa395ec2003-11-02 01:29:27 +00002278 // Only print out used types!
Dan Gohman193c2352008-06-02 21:30:49 +00002279 printContainedStructs(I->second, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002280}
2281
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002282// Push the struct onto the stack and recursively push all structs
2283// this one depends on.
Robert Bocchinob78e8382006-01-20 20:43:57 +00002284//
Reid Spencerac9dcb92007-02-15 03:39:18 +00002285// TODO: Make this work properly with vector types
Robert Bocchinob78e8382006-01-20 20:43:57 +00002286//
Chris Lattner2c601a72002-09-20 15:05:40 +00002287void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman193c2352008-06-02 21:30:49 +00002288 std::set<const Type*> &StructPrinted) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002289 // Don't walk through pointers.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002290 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isIntegerTy())
2291 return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002292
2293 // Print all contained types first.
2294 for (Type::subtype_iterator I = Ty->subtype_begin(),
2295 E = Ty->subtype_end(); I != E; ++I)
2296 printContainedStructs(*I, StructPrinted);
2297
Dan Gohman193c2352008-06-02 21:30:49 +00002298 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002299 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002300 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002301 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002302 std::string Name = TypeNames[Ty];
2303 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002304 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002305 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002306 }
2307}
2308
Chris Lattner4cda8352002-08-20 16:55:48 +00002309void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002310 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002311 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002312
Rafael Espindolabb46f522009-01-15 20:18:42 +00002313 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002314 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2315 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002316 switch (F->getCallingConv()) {
2317 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002318 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002319 break;
2320 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002321 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002322 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002323 default:
2324 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002325 }
2326
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002327 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002328 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002329 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002330
2331 std::stringstream FunctionInnards;
2332
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002333 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002334 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002335
Chris Lattner0c54d892006-05-23 23:39:48 +00002336 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002337 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002338 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002339 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002340 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002341
2342 // If this is a struct-return function, don't print the hidden
2343 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002344 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002345 assert(I != E && "Invalid struct return function!");
2346 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002347 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002348 }
2349
Chris Lattneredd8ce12003-05-03 03:14:35 +00002350 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002351 for (; I != E; ++I) {
2352 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002353 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002354 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002355 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002356 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002357 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002358 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002359 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002360 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002361 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002362 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002363 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002364 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002365 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002366 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002367 }
2368 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002369 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002370 // Loop over the arguments, printing them.
2371 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002372 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002373
2374 // If this is a struct-return function, don't print the hidden
2375 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002376 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002377 assert(I != E && "Invalid struct return function!");
2378 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002379 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002380 }
2381
2382 for (; I != E; ++I) {
2383 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002384 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002385 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng3d794782008-01-11 23:10:11 +00002386 assert(isa<PointerType>(ArgTy));
2387 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2388 }
2389 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002390 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002391 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002392 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002393 }
2394 }
2395
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002396 // Finish printing arguments... if this is a vararg function, print the ...,
2397 // unless there are no known types, in which case, we just emit ().
2398 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002399 if (FT->isVarArg() && PrintedArg) {
2400 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002401 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002402 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002403 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002404 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002405 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002406
2407 // Get the return tpe for the function.
2408 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002409 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002410 RetTy = F->getReturnType();
2411 else {
2412 // If this is a struct-return function, print the struct-return type.
2413 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2414 }
2415
2416 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002417 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002418 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002419 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002420}
2421
Reid Spencer22586642006-12-17 20:24:50 +00002422static inline bool isFPIntBitCast(const Instruction &I) {
2423 if (!isa<BitCastInst>(I))
2424 return false;
2425 const Type *SrcTy = I.getOperand(0)->getType();
2426 const Type *DstTy = I.getType();
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002427 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2428 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
Reid Spencer22586642006-12-17 20:24:50 +00002429}
2430
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002431void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002432 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002433 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002434
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002435 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002436 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002437
2438 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002439 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002440 const Type *StructTy =
2441 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2442 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002443 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002444 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002445
Chris Lattner0c54d892006-05-23 23:39:48 +00002446 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002447 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002448 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002449 Out << " = &StructReturn;\n";
2450 }
2451
2452 bool PrintedVar = false;
2453
Chris Lattner497e19a2002-05-09 20:39:03 +00002454 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002455 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002456 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002457 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002458 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002459 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002460 PrintedVar = true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002461 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2462 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002463 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002464 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002465 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002466
Chris Lattner84e66652003-05-03 07:11:00 +00002467 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2468 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002469 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002470 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002471 Out << ";\n";
2472 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002473 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002474 }
2475 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002476 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002477 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002478 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002479 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002480 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002481 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002482 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002483 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002484
Chris Lattner0c54d892006-05-23 23:39:48 +00002485 if (PrintedVar)
2486 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002487
Chris Lattner395fd592004-12-13 21:52:52 +00002488 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002489 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002490
Chris Lattner16c7bb22002-05-09 02:28:59 +00002491 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002492 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002493 if (Loop *L = LI->getLoopFor(BB)) {
2494 if (L->getHeader() == BB && L->getParentLoop() == 0)
2495 printLoop(L);
2496 } else {
2497 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002498 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002499 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002500
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002501 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002502}
2503
Chris Lattnercb3ad012004-05-09 20:41:32 +00002504void CWriter::printLoop(Loop *L) {
2505 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2506 << "' to make GCC happy */\n";
2507 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2508 BasicBlock *BB = L->getBlocks()[i];
2509 Loop *BBLoop = LI->getLoopFor(BB);
2510 if (BBLoop == L)
2511 printBasicBlock(BB);
2512 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002513 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002514 }
2515 Out << " } while (1); /* end of syntactic loop '"
2516 << L->getHeader()->getName() << "' */\n";
2517}
2518
2519void CWriter::printBasicBlock(BasicBlock *BB) {
2520
2521 // Don't print the label for the basic block if there are no uses, or if
2522 // the only terminator use is the predecessor basic block's terminator.
2523 // We have to scan the use list because PHI nodes use basic blocks too but
2524 // do not require a label to be generated.
2525 //
2526 bool NeedsLabel = false;
2527 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2528 if (isGotoCodeNecessary(*PI, BB)) {
2529 NeedsLabel = true;
2530 break;
2531 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002532
Bill Wendling145aad02007-02-23 22:45:08 +00002533 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002534
Chris Lattnercb3ad012004-05-09 20:41:32 +00002535 // Output all of the instructions in the basic block...
2536 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2537 ++II) {
2538 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002539 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2540 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002541 outputLValue(II);
2542 else
2543 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002544 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002545 Out << ";\n";
2546 }
2547 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002548
Chris Lattnere56d9462008-05-31 09:23:55 +00002549 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002550 visit(*BB->getTerminator());
2551}
2552
2553
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002554// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002555// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002556//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002557void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002558 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002559 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002560
2561 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002562 Out << " return StructReturn;\n";
2563 return;
2564 }
2565
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002566 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002567 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002568 &*--I.getParent()->getParent()->end() == I.getParent() &&
2569 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002570 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002571 }
Chris Lattner44408262002-05-09 03:50:42 +00002572
Dan Gohman76612792008-04-23 21:49:29 +00002573 if (I.getNumOperands() > 1) {
2574 Out << " {\n";
2575 Out << " ";
2576 printType(Out, I.getParent()->getParent()->getReturnType());
2577 Out << " llvm_cbe_mrv_temp = {\n";
2578 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2579 Out << " ";
2580 writeOperand(I.getOperand(i));
2581 if (i != e - 1)
2582 Out << ",";
2583 Out << "\n";
2584 }
2585 Out << " };\n";
2586 Out << " return llvm_cbe_mrv_temp;\n";
2587 Out << " }\n";
2588 return;
2589 }
2590
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002591 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002592 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002593 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002594 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002595 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002596 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002597}
2598
Chris Lattnera9f5e052003-04-22 20:19:52 +00002599void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002600
Chris Lattnera9f5e052003-04-22 20:19:52 +00002601 Out << " switch (";
2602 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002603 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002604 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002605 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002606 Out << ";\n";
2607 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2608 Out << " case ";
2609 writeOperand(SI.getOperand(i));
2610 Out << ":\n";
2611 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002612 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002613 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002614 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002615 Out << " break;\n";
2616 }
2617 Out << " }\n";
2618}
2619
Chris Lattnerab21db72009-10-28 00:19:10 +00002620void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattnerf0dca282009-10-27 21:21:06 +00002621 Out << " goto *(void*)(";
2622 writeOperand(IBI.getOperand(0));
2623 Out << ");\n";
2624}
2625
Chris Lattnera9d12c02004-10-16 18:12:13 +00002626void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002627 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002628}
2629
Chris Lattnercb3ad012004-05-09 20:41:32 +00002630bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2631 /// FIXME: This should be reenabled, but loop reordering safe!!
2632 return true;
2633
Chris Lattner7896c9f2009-12-03 00:50:42 +00002634 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Chris Lattner67c2d182005-03-18 16:12:37 +00002635 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002636
2637 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002638
Chris Lattnercb3ad012004-05-09 20:41:32 +00002639 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002640 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002641 return false;
2642}
2643
John Criswell57bbfce2004-10-20 14:38:39 +00002644void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002645 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002646 unsigned Indent) {
2647 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2648 PHINode *PN = cast<PHINode>(I);
2649 // Now we have to do the printing.
2650 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2651 if (!isa<UndefValue>(IV)) {
2652 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002653 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002654 writeOperand(IV);
2655 Out << "; /* for PHI node */\n";
2656 }
2657 }
2658}
2659
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002660void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002661 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002662 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002663 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002664 writeOperand(Succ);
2665 Out << ";\n";
2666 }
2667}
2668
Misha Brukman37f92e22003-09-11 22:34:13 +00002669// Branch instruction printing - Avoid printing out a branch to a basic block
2670// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002671//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002672void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002673
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002674 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002675 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002676 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002677 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002678 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002679
John Criswell57bbfce2004-10-20 14:38:39 +00002680 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002681 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002682
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002683 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002684 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002685 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002686 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002687 }
2688 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002689 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002690 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002691 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002692 Out << ") {\n";
2693
John Criswell57bbfce2004-10-20 14:38:39 +00002694 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002695 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002696 }
2697
2698 Out << " }\n";
2699 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002700 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002701 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002702 }
2703 Out << "\n";
2704}
2705
Chris Lattner84e66652003-05-03 07:11:00 +00002706// PHI nodes get copied into temporary values at the end of predecessor basic
2707// blocks. We now need to copy these temporary values into the REAL value for
2708// the PHI.
2709void CWriter::visitPHINode(PHINode &I) {
2710 writeOperand(&I);
2711 Out << "__PHI_TEMPORARY";
2712}
2713
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002714
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002715void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002716 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002717 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002718
2719 // We must cast the results of binary operations which might be promoted.
2720 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002721 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2722 (I.getType() == Type::getInt16Ty(I.getContext()))
2723 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002724 needsCast = true;
2725 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002726 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002727 Out << ")(";
2728 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002729
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002730 // If this is a negation operation, print it out as such. For FP, we don't
2731 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002732 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002733 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002734 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002735 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002736 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002737 Out << "-(";
2738 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2739 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002740 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002741 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002742 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002743 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002744 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002745 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002746 else // all 3 flavors of long double
2747 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002748 writeOperand(I.getOperand(0));
2749 Out << ", ";
2750 writeOperand(I.getOperand(1));
2751 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002752 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002753
2754 // Write out the cast of the instruction's value back to the proper type
2755 // if necessary.
2756 bool NeedsClosingParens = writeInstructionCast(I);
2757
2758 // Certain instructions require the operand to be forced to a specific type
2759 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2760 // below for operand 1
2761 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002762
2763 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002764 case Instruction::Add:
2765 case Instruction::FAdd: Out << " + "; break;
2766 case Instruction::Sub:
2767 case Instruction::FSub: Out << " - "; break;
2768 case Instruction::Mul:
2769 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002770 case Instruction::URem:
2771 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002772 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002773 case Instruction::UDiv:
2774 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002775 case Instruction::FDiv: Out << " / "; break;
2776 case Instruction::And: Out << " & "; break;
2777 case Instruction::Or: Out << " | "; break;
2778 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002779 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002780 case Instruction::LShr:
2781 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002782 default:
2783#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002784 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002785#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002786 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002787 }
2788
Reid Spencer1628cec2006-10-26 06:15:43 +00002789 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2790 if (NeedsClosingParens)
2791 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002792 }
2793
Brian Gaeke031a1122003-06-23 20:00:51 +00002794 if (needsCast) {
2795 Out << "))";
2796 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002797}
2798
Reid Spencere4d87aa2006-12-23 06:05:41 +00002799void CWriter::visitICmpInst(ICmpInst &I) {
2800 // We must cast the results of icmp which might be promoted.
2801 bool needsCast = false;
2802
2803 // Write out the cast of the instruction's value back to the proper type
2804 // if necessary.
2805 bool NeedsClosingParens = writeInstructionCast(I);
2806
2807 // Certain icmp predicate require the operand to be forced to a specific type
2808 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2809 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002810 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002811
2812 switch (I.getPredicate()) {
2813 case ICmpInst::ICMP_EQ: Out << " == "; break;
2814 case ICmpInst::ICMP_NE: Out << " != "; break;
2815 case ICmpInst::ICMP_ULE:
2816 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2817 case ICmpInst::ICMP_UGE:
2818 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2819 case ICmpInst::ICMP_ULT:
2820 case ICmpInst::ICMP_SLT: Out << " < "; break;
2821 case ICmpInst::ICMP_UGT:
2822 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002823 default:
2824#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002825 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002826#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002827 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002828 }
2829
Chris Lattner5bda9e42007-09-15 06:51:03 +00002830 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002831 if (NeedsClosingParens)
2832 Out << "))";
2833
2834 if (needsCast) {
2835 Out << "))";
2836 }
2837}
2838
2839void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002840 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2841 Out << "0";
2842 return;
2843 }
2844 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2845 Out << "1";
2846 return;
2847 }
2848
2849 const char* op = 0;
2850 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002851 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002852 case FCmpInst::FCMP_ORD: op = "ord"; break;
2853 case FCmpInst::FCMP_UNO: op = "uno"; break;
2854 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2855 case FCmpInst::FCMP_UNE: op = "une"; break;
2856 case FCmpInst::FCMP_ULT: op = "ult"; break;
2857 case FCmpInst::FCMP_ULE: op = "ule"; break;
2858 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2859 case FCmpInst::FCMP_UGE: op = "uge"; break;
2860 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2861 case FCmpInst::FCMP_ONE: op = "one"; break;
2862 case FCmpInst::FCMP_OLT: op = "olt"; break;
2863 case FCmpInst::FCMP_OLE: op = "ole"; break;
2864 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2865 case FCmpInst::FCMP_OGE: op = "oge"; break;
2866 }
2867
2868 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002869 // Write the first operand
2870 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002871 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002872 // Write the second operand
2873 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002874 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002875}
2876
Reid Spencer555a0b12006-12-11 20:39:15 +00002877static const char * getFloatBitCastField(const Type *Ty) {
2878 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002879 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002880 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002881 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002882 case Type::IntegerTyID: {
2883 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2884 if (NumBits <= 32)
2885 return "Int32";
2886 else
2887 return "Int64";
2888 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002889 }
2890}
2891
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002892void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002893 const Type *DstTy = I.getType();
2894 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002895 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002896 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002897 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002898 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002899 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2900 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002901 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002902 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002903 Out << ')';
2904 return;
2905 }
2906
2907 Out << '(';
2908 printCast(I.getOpcode(), SrcTy, DstTy);
2909
2910 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002911 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2912 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002913 Out << "0-";
2914
2915 writeOperand(I.getOperand(0));
2916
Owen Anderson1d0be152009-08-13 21:58:54 +00002917 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002918 (I.getOpcode() == Instruction::Trunc ||
2919 I.getOpcode() == Instruction::FPToUI ||
2920 I.getOpcode() == Instruction::FPToSI ||
2921 I.getOpcode() == Instruction::PtrToInt)) {
2922 // Make sure we really get a trunc to bool by anding the operand with 1
2923 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002924 }
Chris Lattner72623362007-05-03 02:57:13 +00002925 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002926}
2927
Chris Lattner9f24a072004-03-12 05:52:14 +00002928void CWriter::visitSelectInst(SelectInst &I) {
2929 Out << "((";
2930 writeOperand(I.getCondition());
2931 Out << ") ? (";
2932 writeOperand(I.getTrueValue());
2933 Out << ") : (";
2934 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002935 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002936}
2937
2938
Chris Lattnerc2421432004-05-09 04:30:20 +00002939void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002940 // This is used to keep track of intrinsics that get generated to a lowered
2941 // function. We must generate the prototypes before the function body which
2942 // will only be expanded on first use (by the loop below).
2943 std::vector<Function*> prototypesToGen;
2944
2945 // Examine all the instructions in this function to find the intrinsics that
2946 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002947 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002948 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2949 if (CallInst *CI = dyn_cast<CallInst>(I++))
2950 if (Function *F = CI->getCalledFunction())
2951 switch (F->getIntrinsicID()) {
2952 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002953 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002954 case Intrinsic::vastart:
2955 case Intrinsic::vacopy:
2956 case Intrinsic::vaend:
2957 case Intrinsic::returnaddress:
2958 case Intrinsic::frameaddress:
2959 case Intrinsic::setjmp:
2960 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002961 case Intrinsic::prefetch:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002962 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002963 case Intrinsic::x86_sse_cmp_ss:
2964 case Intrinsic::x86_sse_cmp_ps:
2965 case Intrinsic::x86_sse2_cmp_sd:
2966 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002967 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002968 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002969 break;
2970 default:
Chris Lattner87242152006-03-13 23:09:05 +00002971 // If this is an intrinsic that directly corresponds to a GCC
2972 // builtin, we handle it.
2973 const char *BuiltinName = "";
2974#define GET_GCC_BUILTIN_NAME
2975#include "llvm/Intrinsics.gen"
2976#undef GET_GCC_BUILTIN_NAME
2977 // If we handle it, don't lower it.
2978 if (BuiltinName[0]) break;
2979
Chris Lattnerc2421432004-05-09 04:30:20 +00002980 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002981 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002982 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002983 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002984
Reid Spencer519e2392007-01-29 17:51:02 +00002985 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002986 if (Before) { // Move iterator to instruction after call
2987 I = Before; ++I;
2988 } else {
2989 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002990 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002991 // If the intrinsic got lowered to another call, and that call has
2992 // a definition then we need to make sure its prototype is emitted
2993 // before any calls to it.
2994 if (CallInst *Call = dyn_cast<CallInst>(I))
2995 if (Function *NewF = Call->getCalledFunction())
2996 if (!NewF->isDeclaration())
2997 prototypesToGen.push_back(NewF);
2998
Chris Lattner87242152006-03-13 23:09:05 +00002999 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00003000 }
Chris Lattner4ef51372004-02-14 00:31:10 +00003001
Reid Spencer69f80a62007-04-12 21:00:45 +00003002 // We may have collected some prototypes to emit in the loop above.
3003 // Emit them now, before the function that uses them is emitted. But,
3004 // be careful not to emit them twice.
3005 std::vector<Function*>::iterator I = prototypesToGen.begin();
3006 std::vector<Function*>::iterator E = prototypesToGen.end();
3007 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00003008 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00003009 Out << '\n';
3010 printFunctionSignature(*I, true);
3011 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00003012 }
3013 }
3014}
Chris Lattner4ef51372004-02-14 00:31:10 +00003015
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003016void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003017 if (isa<InlineAsm>(I.getOperand(0)))
3018 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003019
Chris Lattner87242152006-03-13 23:09:05 +00003020 bool WroteCallee = false;
3021
Chris Lattner18ac3c82003-05-08 18:41:45 +00003022 // Handle intrinsic function calls first...
3023 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00003024 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3025 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00003026 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00003027
Chris Lattner4394d512004-11-13 22:21:56 +00003028 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00003029
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003030 const PointerType *PTy = cast<PointerType>(Callee->getType());
3031 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3032
Chris Lattner0c54d892006-05-23 23:39:48 +00003033 // If this is a call to a struct-return function, assign to the first
3034 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00003035 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00003036 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00003037 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00003038 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003039 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00003040 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003041 }
3042
Chris Lattnerfe673d92005-05-06 06:53:07 +00003043 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003044
3045 if (!WroteCallee) {
3046 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00003047 // the pointer. Ditto for indirect calls with byval arguments.
3048 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00003049
Chris Lattner0c54d892006-05-23 23:39:48 +00003050 // GCC is a real PITA. It does not permit codegening casts of functions to
3051 // function pointers if they are in a call (it generates a trap instruction
3052 // instead!). We work around this by inserting a cast to void* in between
3053 // the function and the function pointer cast. Unfortunately, we can't just
3054 // form the constant expression here, because the folder will immediately
3055 // nuke it.
3056 //
3057 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3058 // that void* and function pointers have the same size. :( To deal with this
3059 // in the common case, we handle casts where the number of arguments passed
3060 // match exactly.
3061 //
3062 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00003063 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00003064 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3065 NeedsCast = true;
3066 Callee = RF;
3067 }
3068
3069 if (NeedsCast) {
3070 // Ok, just cast the pointer type.
3071 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00003072 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00003073 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00003074 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00003075 else if (hasByVal)
3076 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3077 else
3078 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00003079 Out << ")(void*)";
3080 }
3081 writeOperand(Callee);
3082 if (NeedsCast) Out << ')';
3083 }
3084
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003085 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003086
Chris Lattner4394d512004-11-13 22:21:56 +00003087 unsigned NumDeclaredParams = FTy->getNumParams();
3088
Chris Lattner0c54d892006-05-23 23:39:48 +00003089 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3090 unsigned ArgNo = 0;
3091 if (isStructRet) { // Skip struct return argument.
3092 ++AI;
3093 ++ArgNo;
3094 }
3095
3096 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00003097 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00003098 if (PrintedArg) Out << ", ";
3099 if (ArgNo < NumDeclaredParams &&
3100 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003101 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00003102 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003103 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003104 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003105 }
Evan Cheng3d794782008-01-11 23:10:11 +00003106 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003107 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003108 writeOperandDeref(*AI);
3109 else
3110 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003111 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003112 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003113 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003114}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003115
Chris Lattner2299fec2008-03-02 08:29:41 +00003116/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
Dan Gohmanf451cb82010-02-10 16:03:48 +00003117/// if the entire call is handled, return false if it wasn't handled, and
Chris Lattner2299fec2008-03-02 08:29:41 +00003118/// optionally set 'WroteCallee' if the callee has already been printed out.
3119bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3120 bool &WroteCallee) {
3121 switch (ID) {
3122 default: {
3123 // If this is an intrinsic that directly corresponds to a GCC
3124 // builtin, we emit it here.
3125 const char *BuiltinName = "";
3126 Function *F = I.getCalledFunction();
3127#define GET_GCC_BUILTIN_NAME
3128#include "llvm/Intrinsics.gen"
3129#undef GET_GCC_BUILTIN_NAME
3130 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3131
3132 Out << BuiltinName;
3133 WroteCallee = true;
3134 return false;
3135 }
3136 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003137 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003138 return true;
3139 case Intrinsic::vastart:
3140 Out << "0; ";
3141
3142 Out << "va_start(*(va_list*)";
3143 writeOperand(I.getOperand(1));
3144 Out << ", ";
3145 // Output the last argument to the enclosing function.
3146 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00003147 std::string msg;
3148 raw_string_ostream Msg(msg);
3149 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00003150 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00003151 << I.getParent()->getParent()->getName() << "'!";
3152 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00003153 }
3154 writeOperand(--I.getParent()->getParent()->arg_end());
3155 Out << ')';
3156 return true;
3157 case Intrinsic::vaend:
3158 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3159 Out << "0; va_end(*(va_list*)";
3160 writeOperand(I.getOperand(1));
3161 Out << ')';
3162 } else {
3163 Out << "va_end(*(va_list*)0)";
3164 }
3165 return true;
3166 case Intrinsic::vacopy:
3167 Out << "0; ";
3168 Out << "va_copy(*(va_list*)";
3169 writeOperand(I.getOperand(1));
3170 Out << ", *(va_list*)";
3171 writeOperand(I.getOperand(2));
3172 Out << ')';
3173 return true;
3174 case Intrinsic::returnaddress:
3175 Out << "__builtin_return_address(";
3176 writeOperand(I.getOperand(1));
3177 Out << ')';
3178 return true;
3179 case Intrinsic::frameaddress:
3180 Out << "__builtin_frame_address(";
3181 writeOperand(I.getOperand(1));
3182 Out << ')';
3183 return true;
3184 case Intrinsic::powi:
3185 Out << "__builtin_powi(";
3186 writeOperand(I.getOperand(1));
3187 Out << ", ";
3188 writeOperand(I.getOperand(2));
3189 Out << ')';
3190 return true;
3191 case Intrinsic::setjmp:
3192 Out << "setjmp(*(jmp_buf*)";
3193 writeOperand(I.getOperand(1));
3194 Out << ')';
3195 return true;
3196 case Intrinsic::longjmp:
3197 Out << "longjmp(*(jmp_buf*)";
3198 writeOperand(I.getOperand(1));
3199 Out << ", ";
3200 writeOperand(I.getOperand(2));
3201 Out << ')';
3202 return true;
3203 case Intrinsic::prefetch:
3204 Out << "LLVM_PREFETCH((const void *)";
3205 writeOperand(I.getOperand(1));
3206 Out << ", ";
3207 writeOperand(I.getOperand(2));
3208 Out << ", ";
3209 writeOperand(I.getOperand(3));
3210 Out << ")";
3211 return true;
3212 case Intrinsic::stacksave:
3213 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3214 // to work around GCC bugs (see PR1809).
3215 Out << "0; *((void**)&" << GetValueName(&I)
3216 << ") = __builtin_stack_save()";
3217 return true;
Chris Lattner4e220122008-03-02 08:47:13 +00003218 case Intrinsic::x86_sse_cmp_ss:
3219 case Intrinsic::x86_sse_cmp_ps:
3220 case Intrinsic::x86_sse2_cmp_sd:
3221 case Intrinsic::x86_sse2_cmp_pd:
3222 Out << '(';
3223 printType(Out, I.getType());
3224 Out << ')';
3225 // Multiple GCC builtins multiplex onto this intrinsic.
3226 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003227 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003228 case 0: Out << "__builtin_ia32_cmpeq"; break;
3229 case 1: Out << "__builtin_ia32_cmplt"; break;
3230 case 2: Out << "__builtin_ia32_cmple"; break;
3231 case 3: Out << "__builtin_ia32_cmpunord"; break;
3232 case 4: Out << "__builtin_ia32_cmpneq"; break;
3233 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3234 case 6: Out << "__builtin_ia32_cmpnle"; break;
3235 case 7: Out << "__builtin_ia32_cmpord"; break;
3236 }
3237 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3238 Out << 'p';
3239 else
3240 Out << 's';
3241 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3242 Out << 's';
3243 else
3244 Out << 'd';
3245
3246 Out << "(";
3247 writeOperand(I.getOperand(1));
3248 Out << ", ";
3249 writeOperand(I.getOperand(2));
3250 Out << ")";
3251 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003252 case Intrinsic::ppc_altivec_lvsl:
3253 Out << '(';
3254 printType(Out, I.getType());
3255 Out << ')';
3256 Out << "__builtin_altivec_lvsl(0, (void*)";
3257 writeOperand(I.getOperand(1));
3258 Out << ")";
3259 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003260 }
3261}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003262
3263//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003264//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003265// of the per target tables
3266// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003267std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003268 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3269
Chris Lattneraf76e592009-08-22 20:48:53 +00003270 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003271 const MCAsmInfo *TargetAsm;
3272 std::string Triple = TheModule->getTargetTriple();
3273 if (Triple.empty())
3274 Triple = llvm::sys::getHostTriple();
3275
3276 std::string E;
3277 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3278 TargetAsm = Match->createAsmInfo(Triple);
3279 else
3280 return c.Codes[0];
3281
3282 const char *const *table = TargetAsm->getAsmCBE();
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003283
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003284 // Search the translation table if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003285 for (int i = 0; table && table[i]; i += 2)
Chris Lattnerc0dba722010-01-17 18:22:35 +00003286 if (c.Codes[0] == table[i]) {
3287 delete TargetAsm;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003288 return table[i+1];
Chris Lattnerc0dba722010-01-17 18:22:35 +00003289 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003290
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003291 // Default is identity.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003292 delete TargetAsm;
Andrew Lenharth85f22282006-11-28 22:25:32 +00003293 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003294}
3295
3296//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003297static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003298 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3299 if (asmstr[i] == '\n')
3300 asmstr.replace(i, 1, "\\n");
3301 else if (asmstr[i] == '\t')
3302 asmstr.replace(i, 1, "\\t");
3303 else if (asmstr[i] == '$') {
3304 if (asmstr[i + 1] == '{') {
3305 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3306 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3307 std::string n = "%" +
3308 asmstr.substr(a + 1, b - a - 1) +
3309 asmstr.substr(i + 2, a - i - 2);
3310 asmstr.replace(i, b - i + 1, n);
3311 i += n.size() - 1;
3312 } else
3313 asmstr.replace(i, 1, "%");
3314 }
3315 else if (asmstr[i] == '%')//grr
3316 { asmstr.replace(i, 1, "%%"); ++i;}
3317
3318 return asmstr;
3319}
3320
Andrew Lenharth238581f2006-11-28 19:56:02 +00003321//TODO: assumptions about what consume arguments from the call are likely wrong
3322// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003323void CWriter::visitInlineAsm(CallInst &CI) {
3324 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003325 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003326
3327 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00003328 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003329 ;
3330 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3331 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3332 ResultVals.push_back(std::make_pair(&CI, (int)i));
3333 } else {
3334 ResultVals.push_back(std::make_pair(&CI, -1));
3335 }
3336
Chris Lattner67f631d2008-06-04 18:03:28 +00003337 // Fix up the asm string for gcc and emit it.
3338 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3339 Out << " :";
3340
3341 unsigned ValueCount = 0;
3342 bool IsFirst = true;
3343
3344 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003345 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003346 E = Constraints.end(); I != E; ++I) {
3347
3348 if (I->Type != InlineAsm::isOutput) {
3349 ++ValueCount;
3350 continue; // Ignore non-output constraints.
3351 }
3352
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003353 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003354 std::string C = InterpretASMConstraint(*I);
3355 if (C.empty()) continue;
3356
Chris Lattner67f631d2008-06-04 18:03:28 +00003357 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003358 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003359 IsFirst = false;
3360 }
3361
3362 // Unpack the dest.
3363 Value *DestVal;
3364 int DestValNo = -1;
3365
3366 if (ValueCount < ResultVals.size()) {
3367 DestVal = ResultVals[ValueCount].first;
3368 DestValNo = ResultVals[ValueCount].second;
3369 } else
3370 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3371
3372 if (I->isEarlyClobber)
3373 C = "&"+C;
3374
3375 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3376 if (DestValNo != -1)
3377 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003378 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003379 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003380 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003381
3382
3383 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003384 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003385 IsFirst = true;
3386 ValueCount = 0;
3387 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3388 E = Constraints.end(); I != E; ++I) {
3389 if (I->Type != InlineAsm::isInput) {
3390 ++ValueCount;
3391 continue; // Ignore non-input constraints.
3392 }
3393
3394 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3395 std::string C = InterpretASMConstraint(*I);
3396 if (C.empty()) continue;
3397
3398 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003399 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003400 IsFirst = false;
3401 }
3402
3403 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3404 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3405
3406 Out << "\"" << C << "\"(";
3407 if (!I->isIndirect)
3408 writeOperand(SrcVal);
3409 else
3410 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003411 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003412 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003413
3414 // Convert over the clobber constraints.
3415 IsFirst = true;
Chris Lattner67f631d2008-06-04 18:03:28 +00003416 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3417 E = Constraints.end(); I != E; ++I) {
3418 if (I->Type != InlineAsm::isClobber)
3419 continue; // Ignore non-input constraints.
3420
3421 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3422 std::string C = InterpretASMConstraint(*I);
3423 if (C.empty()) continue;
3424
3425 if (!IsFirst) {
3426 Out << ", ";
3427 IsFirst = false;
3428 }
3429
3430 Out << '\"' << C << '"';
3431 }
3432
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003433 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003434}
3435
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003436void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003437 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003438 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003439 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003440 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003441 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003442 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003443 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003444 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003445 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003446 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003447}
3448
Chris Lattnere05252b42008-03-02 08:07:24 +00003449void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003450 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003451
3452 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003453 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003454 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003455 return;
3456 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003457
3458 // Find out if the last index is into a vector. If so, we have to print this
3459 // specially. Since vectors can't have elements of indexable type, only the
3460 // last index could possibly be of a vector element.
3461 const VectorType *LastIndexIsVector = 0;
3462 {
3463 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3464 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003465 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003466
3467 Out << "(";
3468
3469 // If the last index is into a vector, we can't print it as &a[i][j] because
3470 // we can't index into a vector with j in GCC. Instead, emit this as
3471 // (((float*)&a[i])+j)
3472 if (LastIndexIsVector) {
3473 Out << "((";
3474 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3475 Out << ")(";
3476 }
3477
3478 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003479
Chris Lattnere05252b42008-03-02 08:07:24 +00003480 // If the first index is 0 (very typical) we can do a number of
3481 // simplifications to clean up the code.
3482 Value *FirstOp = I.getOperand();
3483 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3484 // First index isn't simple, print it the hard way.
3485 writeOperand(Ptr);
3486 } else {
3487 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003488
Chris Lattnere05252b42008-03-02 08:07:24 +00003489 // Okay, emit the first operand. If Ptr is something that is already address
3490 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3491 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003492 writeOperandInternal(Ptr, Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00003493 } else if (I != E && isa<StructType>(*I)) {
3494 // If we didn't already emit the first operand, see if we can print it as
3495 // P->f instead of "P[0].f"
3496 writeOperand(Ptr);
3497 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3498 ++I; // eat the struct index as well.
3499 } else {
3500 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3501 Out << "(*";
3502 writeOperand(Ptr);
3503 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003504 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003505 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003506
Chris Lattnere05252b42008-03-02 08:07:24 +00003507 for (; I != E; ++I) {
Chris Lattner23e90702003-11-25 20:49:55 +00003508 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003509 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman193c2352008-06-02 21:30:49 +00003510 } else if (isa<ArrayType>(*I)) {
3511 Out << ".array[";
3512 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3513 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003514 } else if (!isa<VectorType>(*I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003515 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003516 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003517 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003518 } else {
3519 // If the last index is into a vector, then print it out as "+j)". This
3520 // works with the 'LastIndexIsVector' code above.
3521 if (isa<Constant>(I.getOperand()) &&
3522 cast<Constant>(I.getOperand())->isNullValue()) {
3523 Out << "))"; // avoid "+0".
3524 } else {
3525 Out << ")+(";
3526 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3527 Out << "))";
3528 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003529 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003530 }
3531 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003532}
3533
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003534void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3535 bool IsVolatile, unsigned Alignment) {
3536
3537 bool IsUnaligned = Alignment &&
3538 Alignment < TD->getABITypeAlignment(OperandType);
3539
3540 if (!IsUnaligned)
3541 Out << '*';
3542 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003543 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003544 if (IsUnaligned)
3545 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3546 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3547 if (IsUnaligned) {
3548 Out << "; } ";
3549 if (IsVolatile) Out << "volatile ";
3550 Out << "*";
3551 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003552 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003553 }
3554
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003555 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003556
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003557 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003558 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003559 if (IsUnaligned)
3560 Out << "->data";
3561 }
3562}
3563
3564void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003565 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3566 I.getAlignment());
3567
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003568}
3569
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003570void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003571 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3572 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003573 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003574 Value *Operand = I.getOperand(0);
3575 Constant *BitMask = 0;
3576 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3577 if (!ITy->isPowerOf2ByteWidth())
3578 // We have a bit width that doesn't match an even power-of-2 byte
3579 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneed707b2009-07-24 23:12:02 +00003580 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003581 if (BitMask)
3582 Out << "((";
3583 writeOperand(Operand);
3584 if (BitMask) {
3585 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003586 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003587 Out << ")";
3588 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003589}
3590
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003591void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003592 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003593 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003594}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003595
Chris Lattner4d45bd02003-10-18 05:57:43 +00003596void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003597 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003598 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003599 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003600 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003601 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003602}
3603
Chris Lattner33a44d92008-03-02 03:52:39 +00003604void CWriter::visitInsertElementInst(InsertElementInst &I) {
3605 const Type *EltTy = I.getType()->getElementType();
3606 writeOperand(I.getOperand(0));
3607 Out << ";\n ";
3608 Out << "((";
3609 printType(Out, PointerType::getUnqual(EltTy));
3610 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003611 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003612 Out << "] = (";
3613 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003614 Out << ")";
3615}
3616
Chris Lattner0452ed62008-03-02 03:57:08 +00003617void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3618 // We know that our operand is not inlined.
3619 Out << "((";
3620 const Type *EltTy =
3621 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3622 printType(Out, PointerType::getUnqual(EltTy));
3623 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3624 writeOperand(I.getOperand(1));
3625 Out << "]";
3626}
3627
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003628void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3629 Out << "(";
3630 printType(Out, SVI.getType());
3631 Out << "){ ";
3632 const VectorType *VT = SVI.getType();
3633 unsigned NumElts = VT->getNumElements();
3634 const Type *EltTy = VT->getElementType();
3635
3636 for (unsigned i = 0; i != NumElts; ++i) {
3637 if (i) Out << ", ";
3638 int SrcVal = SVI.getMaskValue(i);
3639 if ((unsigned)SrcVal >= NumElts*2) {
3640 Out << " 0/*undef*/ ";
3641 } else {
3642 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3643 if (isa<Instruction>(Op)) {
3644 // Do an extractelement of this value from the appropriate input.
3645 Out << "((";
3646 printType(Out, PointerType::getUnqual(EltTy));
3647 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003648 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003649 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3650 Out << "0";
3651 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003652 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003653 (NumElts-1)),
3654 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003655 }
3656 }
3657 }
3658 Out << "}";
3659}
Chris Lattner0452ed62008-03-02 03:57:08 +00003660
Dan Gohman193c2352008-06-02 21:30:49 +00003661void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3662 // Start by copying the entire aggregate value into the result variable.
3663 writeOperand(IVI.getOperand(0));
3664 Out << ";\n ";
3665
3666 // Then do the insert to update the field.
3667 Out << GetValueName(&IVI);
3668 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3669 i != e; ++i) {
3670 const Type *IndexedTy =
3671 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3672 if (isa<ArrayType>(IndexedTy))
3673 Out << ".array[" << *i << "]";
3674 else
3675 Out << ".field" << *i;
3676 }
3677 Out << " = ";
3678 writeOperand(IVI.getOperand(1));
3679}
3680
3681void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3682 Out << "(";
3683 if (isa<UndefValue>(EVI.getOperand(0))) {
3684 Out << "(";
3685 printType(Out, EVI.getType());
3686 Out << ") 0/*UNDEF*/";
3687 } else {
3688 Out << GetValueName(EVI.getOperand(0));
3689 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3690 i != e; ++i) {
3691 const Type *IndexedTy =
3692 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3693 if (isa<ArrayType>(IndexedTy))
3694 Out << ".array[" << *i << "]";
3695 else
3696 Out << ".field" << *i;
3697 }
3698 }
3699 Out << ")";
3700}
3701
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003702//===----------------------------------------------------------------------===//
3703// External Interface declaration
3704//===----------------------------------------------------------------------===//
3705
Chris Lattner1911fd42006-09-04 04:14:57 +00003706bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003707 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003708 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003709 CodeGenOpt::Level OptLevel) {
Chris Lattner211edae2010-02-02 21:06:45 +00003710 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Chris Lattner0431c962005-06-25 02:48:37 +00003711
Gordon Henriksence224772008-01-07 01:30:38 +00003712 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003713 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003714 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003715 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003716 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003717 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003718 return false;
3719}