blob: 5015d1bcce80e3bc6398876ef49bb1e076302e0f [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 Lattner0bd58b02010-01-17 19:32:29 +0000354static std::string MangleType(const std::string &S) {
355 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) {
496 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
497 "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) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000543 assert((Ty->isPrimitiveType() || Ty->isInteger() || 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) {
Owen Andersoncb371882008-08-21 00:14:44 +0000594 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
595 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) {
Chris Lattnerb61d41b2008-03-02 03:33:31 +0000697 if (Ty->isPrimitiveType() || Ty->isInteger() || 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 << "((";
Owen Anderson1d0be152009-08-13 21:58:54 +00001399 if (Ty->isInteger() && 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 Lattneracd03ae2010-01-17 19:23:46 +00001463 return 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();
Owen Anderson1d0be152009-08-13 21:58:54 +00001500 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1501 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
1844 // Otherwise, it it is other metadata, don't print it. This catches things
1845 // 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 Lattner0bd58b02010-01-17 19:32:29 +00002250 std::string Name = "struct " + MangleType("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 Lattner0bd58b02010-01-17 19:32:29 +00002261 std::string Name = MangleType("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.
Chris Lattner42a75512007-01-15 02:27:26 +00002290 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
Chris Lattner14d9b202006-01-20 18:57:03 +00002291
2292 // Print all contained types first.
2293 for (Type::subtype_iterator I = Ty->subtype_begin(),
2294 E = Ty->subtype_end(); I != E; ++I)
2295 printContainedStructs(*I, StructPrinted);
2296
Dan Gohman193c2352008-06-02 21:30:49 +00002297 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002298 // Check to see if we have already printed this struct.
Dan Gohman193c2352008-06-02 21:30:49 +00002299 if (StructPrinted.insert(Ty).second) {
Chris Lattner14d9b202006-01-20 18:57:03 +00002300 // Print structure type out.
Dan Gohman193c2352008-06-02 21:30:49 +00002301 std::string Name = TypeNames[Ty];
2302 printType(Out, Ty, false, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +00002303 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002304 }
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +00002305 }
2306}
2307
Chris Lattner4cda8352002-08-20 16:55:48 +00002308void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002309 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002310 bool isStructReturn = F->hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00002311
Rafael Espindolabb46f522009-01-15 20:18:42 +00002312 if (F->hasLocalLinkage()) Out << "static ";
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002313 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2314 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002315 switch (F->getCallingConv()) {
2316 case CallingConv::X86_StdCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002317 Out << "__attribute__((stdcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002318 break;
2319 case CallingConv::X86_FastCall:
Nick Lewyckyf9ef5b32008-11-26 03:17:27 +00002320 Out << "__attribute__((fastcall)) ";
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002321 break;
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002322 default:
2323 break;
Anton Korobeynikovbcb97702006-09-17 20:25:45 +00002324 }
2325
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002326 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00002327 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Patel05988662008-09-25 21:00:45 +00002328 const AttrListPtr &PAL = F->getAttributes();
Misha Brukmand6a29a52005-04-20 16:05:03 +00002329
2330 std::stringstream FunctionInnards;
2331
Nick Hildenbrandt98502372002-11-18 20:55:50 +00002332 // Print out the name...
Bill Wendling145aad02007-02-23 22:45:08 +00002333 FunctionInnards << GetValueName(F) << '(';
Misha Brukmand6a29a52005-04-20 16:05:03 +00002334
Chris Lattner0c54d892006-05-23 23:39:48 +00002335 bool PrintedArg = false;
Reid Spencer5cbf9852007-01-30 20:08:39 +00002336 if (!F->isDeclaration()) {
Chris Lattnere4d5c442005-03-15 04:54:21 +00002337 if (!F->arg_empty()) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002338 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng681d2b82008-01-11 03:07:46 +00002339 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002340
2341 // If this is a struct-return function, don't print the hidden
2342 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002343 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002344 assert(I != E && "Invalid struct return function!");
2345 ++I;
Evan Cheng681d2b82008-01-11 03:07:46 +00002346 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002347 }
2348
Chris Lattneredd8ce12003-05-03 03:14:35 +00002349 std::string ArgName;
Chris Lattner0c54d892006-05-23 23:39:48 +00002350 for (; I != E; ++I) {
2351 if (PrintedArg) FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +00002352 if (I->hasName() || !Prototype)
Bill Wendling145aad02007-02-23 22:45:08 +00002353 ArgName = GetValueName(I);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002354 else
Chris Lattner4cda8352002-08-20 16:55:48 +00002355 ArgName = "";
Evan Cheng681d2b82008-01-11 03:07:46 +00002356 const Type *ArgTy = I->getType();
Devang Patel05988662008-09-25 21:00:45 +00002357 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng588c6f82008-01-11 09:12:49 +00002358 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattnere05252b42008-03-02 08:07:24 +00002359 ByValParams.insert(I);
Evan Cheng588c6f82008-01-11 09:12:49 +00002360 }
Evan Cheng681d2b82008-01-11 03:07:46 +00002361 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002362 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002363 ArgName);
Chris Lattner0c54d892006-05-23 23:39:48 +00002364 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002365 ++Idx;
Chris Lattnerdeed7a52002-05-09 15:18:52 +00002366 }
2367 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002368 } else {
Chris Lattner0c54d892006-05-23 23:39:48 +00002369 // Loop over the arguments, printing them.
2370 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Cheng3d794782008-01-11 23:10:11 +00002371 unsigned Idx = 1;
Chris Lattner0c54d892006-05-23 23:39:48 +00002372
2373 // If this is a struct-return function, don't print the hidden
2374 // struct-return argument.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002375 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002376 assert(I != E && "Invalid struct return function!");
2377 ++I;
Evan Cheng3d794782008-01-11 23:10:11 +00002378 ++Idx;
Chris Lattner0c54d892006-05-23 23:39:48 +00002379 }
2380
2381 for (; I != E; ++I) {
2382 if (PrintedArg) FunctionInnards << ", ";
Evan Cheng3d794782008-01-11 23:10:11 +00002383 const Type *ArgTy = *I;
Devang Patel05988662008-09-25 21:00:45 +00002384 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng3d794782008-01-11 23:10:11 +00002385 assert(isa<PointerType>(ArgTy));
2386 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2387 }
2388 printType(FunctionInnards, ArgTy,
Devang Patel05988662008-09-25 21:00:45 +00002389 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Chris Lattner0c54d892006-05-23 23:39:48 +00002390 PrintedArg = true;
Reid Spencer0ae96932007-01-07 03:24:48 +00002391 ++Idx;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002392 }
2393 }
2394
Chris Lattner1f8c4a12002-09-20 22:32:30 +00002395 // Finish printing arguments... if this is a vararg function, print the ...,
2396 // unless there are no known types, in which case, we just emit ().
2397 //
Chris Lattner0c54d892006-05-23 23:39:48 +00002398 if (FT->isVarArg() && PrintedArg) {
2399 if (PrintedArg) FunctionInnards << ", ";
Joel Stanley54f60322003-06-25 04:52:09 +00002400 FunctionInnards << "..."; // Output varargs portion of signature!
Chris Lattner0c54d892006-05-23 23:39:48 +00002401 } else if (!FT->isVarArg() && !PrintedArg) {
Chris Lattner4f7e1732003-11-26 00:09:17 +00002402 FunctionInnards << "void"; // ret() -> ret(void) in C.
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002403 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002404 FunctionInnards << ')';
Chris Lattner0c54d892006-05-23 23:39:48 +00002405
2406 // Get the return tpe for the function.
2407 const Type *RetTy;
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002408 if (!isStructReturn)
Chris Lattner0c54d892006-05-23 23:39:48 +00002409 RetTy = F->getReturnType();
2410 else {
2411 // If this is a struct-return function, print the struct-return type.
2412 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2413 }
2414
2415 // Print out the return type and the signature built above.
Reid Spencer30f9e27f2007-01-09 06:38:06 +00002416 printType(Out, RetTy,
Devang Patel05988662008-09-25 21:00:45 +00002417 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Reid Spencer0ae96932007-01-07 03:24:48 +00002418 FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002419}
2420
Reid Spencer22586642006-12-17 20:24:50 +00002421static inline bool isFPIntBitCast(const Instruction &I) {
2422 if (!isa<BitCastInst>(I))
2423 return false;
2424 const Type *SrcTy = I.getOperand(0)->getType();
2425 const Type *DstTy = I.getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002426 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2427 (DstTy->isFloatingPoint() && SrcTy->isInteger());
Reid Spencer22586642006-12-17 20:24:50 +00002428}
2429
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002430void CWriter::printFunction(Function &F) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002431 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel41e23972008-03-03 21:46:28 +00002432 bool isStructReturn = F.hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002433
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002434 printFunctionSignature(&F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002435 Out << " {\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002436
2437 // If this is a struct return function, handle the result with magic.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002438 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002439 const Type *StructTy =
2440 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2441 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002442 printType(Out, StructTy, false, "StructReturn");
Chris Lattner0c54d892006-05-23 23:39:48 +00002443 Out << "; /* Struct return temporary */\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002444
Chris Lattner0c54d892006-05-23 23:39:48 +00002445 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002446 printType(Out, F.arg_begin()->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002447 GetValueName(F.arg_begin()));
Chris Lattner0c54d892006-05-23 23:39:48 +00002448 Out << " = &StructReturn;\n";
2449 }
2450
2451 bool PrintedVar = false;
2452
Chris Lattner497e19a2002-05-09 20:39:03 +00002453 // print local variable information for the function
Reid Spencer941cfda2006-12-17 18:50:51 +00002454 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002455 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +00002456 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002457 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Misha Brukman41ce39c2005-01-31 06:19:57 +00002458 Out << "; /* Address-exposed local */\n";
Chris Lattner0c54d892006-05-23 23:39:48 +00002459 PrintedVar = true;
Owen Anderson1d0be152009-08-13 21:58:54 +00002460 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2461 !isInlinableInst(*I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +00002462 Out << " ";
Bill Wendling145aad02007-02-23 22:45:08 +00002463 printType(Out, I->getType(), false, GetValueName(&*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002464 Out << ";\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002465
Chris Lattner84e66652003-05-03 07:11:00 +00002466 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2467 Out << " ";
Reid Spencer251f2142007-01-09 17:09:09 +00002468 printType(Out, I->getType(), false,
Bill Wendling145aad02007-02-23 22:45:08 +00002469 GetValueName(&*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +00002470 Out << ";\n";
2471 }
Chris Lattner0c54d892006-05-23 23:39:48 +00002472 PrintedVar = true;
Reid Spencer941cfda2006-12-17 18:50:51 +00002473 }
2474 // We need a temporary for the BitCast to use so it can pluck a value out
Reid Spencere4d87aa2006-12-23 06:05:41 +00002475 // of a union to do the BitCast. This is separate from the need for a
Reid Spencer941cfda2006-12-17 18:50:51 +00002476 // variable to hold the result of the BitCast.
Reid Spencer22586642006-12-17 20:24:50 +00002477 if (isFPIntBitCast(*I)) {
Bill Wendling145aad02007-02-23 22:45:08 +00002478 Out << " llvmBitCastUnion " << GetValueName(&*I)
Reid Spencer555a0b12006-12-11 20:39:15 +00002479 << "__BITCAST_TEMPORARY;\n";
Reid Spencer941cfda2006-12-17 18:50:51 +00002480 PrintedVar = true;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002481 }
Reid Spencer941cfda2006-12-17 18:50:51 +00002482 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002483
Chris Lattner0c54d892006-05-23 23:39:48 +00002484 if (PrintedVar)
2485 Out << '\n';
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00002486
Chris Lattner395fd592004-12-13 21:52:52 +00002487 if (F.hasExternalLinkage() && F.getName() == "main")
Chris Lattner50a8a172005-05-06 06:58:42 +00002488 Out << " CODE_FOR_MAIN();\n";
Chris Lattner395fd592004-12-13 21:52:52 +00002489
Chris Lattner16c7bb22002-05-09 02:28:59 +00002490 // print the basic blocks
Chris Lattner94f4f8e2004-02-13 23:00:29 +00002491 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002492 if (Loop *L = LI->getLoopFor(BB)) {
2493 if (L->getHeader() == BB && L->getParentLoop() == 0)
2494 printLoop(L);
2495 } else {
2496 printBasicBlock(BB);
Chris Lattnerd0c668c2002-05-09 21:18:38 +00002497 }
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002498 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002499
Chris Lattner8c3c4bf2002-05-09 15:49:41 +00002500 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002501}
2502
Chris Lattnercb3ad012004-05-09 20:41:32 +00002503void CWriter::printLoop(Loop *L) {
2504 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2505 << "' to make GCC happy */\n";
2506 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2507 BasicBlock *BB = L->getBlocks()[i];
2508 Loop *BBLoop = LI->getLoopFor(BB);
2509 if (BBLoop == L)
2510 printBasicBlock(BB);
2511 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
Misha Brukmand6a29a52005-04-20 16:05:03 +00002512 printLoop(BBLoop);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002513 }
2514 Out << " } while (1); /* end of syntactic loop '"
2515 << L->getHeader()->getName() << "' */\n";
2516}
2517
2518void CWriter::printBasicBlock(BasicBlock *BB) {
2519
2520 // Don't print the label for the basic block if there are no uses, or if
2521 // the only terminator use is the predecessor basic block's terminator.
2522 // We have to scan the use list because PHI nodes use basic blocks too but
2523 // do not require a label to be generated.
2524 //
2525 bool NeedsLabel = false;
2526 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2527 if (isGotoCodeNecessary(*PI, BB)) {
2528 NeedsLabel = true;
2529 break;
2530 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002531
Bill Wendling145aad02007-02-23 22:45:08 +00002532 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002533
Chris Lattnercb3ad012004-05-09 20:41:32 +00002534 // Output all of the instructions in the basic block...
2535 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2536 ++II) {
2537 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002538 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2539 !isInlineAsm(*II))
Chris Lattnercb3ad012004-05-09 20:41:32 +00002540 outputLValue(II);
2541 else
2542 Out << " ";
Chris Lattnere56d9462008-05-31 09:23:55 +00002543 writeInstComputationInline(*II);
Chris Lattnercb3ad012004-05-09 20:41:32 +00002544 Out << ";\n";
2545 }
2546 }
Misha Brukmand6a29a52005-04-20 16:05:03 +00002547
Chris Lattnere56d9462008-05-31 09:23:55 +00002548 // Don't emit prefix or suffix for the terminator.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002549 visit(*BB->getTerminator());
2550}
2551
2552
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002553// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +00002554// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002555//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002556void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002557 // If this is a struct return function, return the temporary struct.
Devang Patel41e23972008-03-03 21:46:28 +00002558 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00002559
2560 if (isStructReturn) {
Chris Lattner0c54d892006-05-23 23:39:48 +00002561 Out << " return StructReturn;\n";
2562 return;
2563 }
2564
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002565 // Don't output a void return if this is the last basic block in the function
Misha Brukmand6a29a52005-04-20 16:05:03 +00002566 if (I.getNumOperands() == 0 &&
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002567 &*--I.getParent()->getParent()->end() == I.getParent() &&
2568 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002569 return;
Chris Lattner963b70b2002-05-21 18:05:19 +00002570 }
Chris Lattner44408262002-05-09 03:50:42 +00002571
Dan Gohman76612792008-04-23 21:49:29 +00002572 if (I.getNumOperands() > 1) {
2573 Out << " {\n";
2574 Out << " ";
2575 printType(Out, I.getParent()->getParent()->getReturnType());
2576 Out << " llvm_cbe_mrv_temp = {\n";
2577 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2578 Out << " ";
2579 writeOperand(I.getOperand(i));
2580 if (i != e - 1)
2581 Out << ",";
2582 Out << "\n";
2583 }
2584 Out << " };\n";
2585 Out << " return llvm_cbe_mrv_temp;\n";
2586 Out << " }\n";
2587 return;
2588 }
2589
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002590 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002591 if (I.getNumOperands()) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00002592 Out << ' ';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002593 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +00002594 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002595 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002596}
2597
Chris Lattnera9f5e052003-04-22 20:19:52 +00002598void CWriter::visitSwitchInst(SwitchInst &SI) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002599
Chris Lattnera9f5e052003-04-22 20:19:52 +00002600 Out << " switch (";
2601 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +00002602 Out << ") {\n default:\n";
John Criswell30cc2272004-10-25 18:30:09 +00002603 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnerf1acd962003-04-23 19:15:13 +00002604 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002605 Out << ";\n";
2606 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2607 Out << " case ";
2608 writeOperand(SI.getOperand(i));
2609 Out << ":\n";
2610 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
John Criswell30cc2272004-10-25 18:30:09 +00002611 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +00002612 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002613 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Chris Lattnera9f5e052003-04-22 20:19:52 +00002614 Out << " break;\n";
2615 }
2616 Out << " }\n";
2617}
2618
Chris Lattnerab21db72009-10-28 00:19:10 +00002619void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattnerf0dca282009-10-27 21:21:06 +00002620 Out << " goto *(void*)(";
2621 writeOperand(IBI.getOperand(0));
2622 Out << ");\n";
2623}
2624
Chris Lattnera9d12c02004-10-16 18:12:13 +00002625void CWriter::visitUnreachableInst(UnreachableInst &I) {
Chris Lattner963869e2004-10-17 23:49:11 +00002626 Out << " /*UNREACHABLE*/;\n";
Chris Lattnera9d12c02004-10-16 18:12:13 +00002627}
2628
Chris Lattnercb3ad012004-05-09 20:41:32 +00002629bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2630 /// FIXME: This should be reenabled, but loop reordering safe!!
2631 return true;
2632
Chris Lattner7896c9f2009-12-03 00:50:42 +00002633 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Chris Lattner67c2d182005-03-18 16:12:37 +00002634 return true; // Not the direct successor, we need a goto.
Chris Lattnercb3ad012004-05-09 20:41:32 +00002635
2636 //isa<SwitchInst>(From->getTerminator())
Chris Lattner9bda5f52003-06-28 17:53:05 +00002637
Chris Lattnercb3ad012004-05-09 20:41:32 +00002638 if (LI->getLoopFor(From) != LI->getLoopFor(To))
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002639 return true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002640 return false;
2641}
2642
John Criswell57bbfce2004-10-20 14:38:39 +00002643void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
Misha Brukmand6a29a52005-04-20 16:05:03 +00002644 BasicBlock *Successor,
John Criswell57bbfce2004-10-20 14:38:39 +00002645 unsigned Indent) {
2646 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2647 PHINode *PN = cast<PHINode>(I);
2648 // Now we have to do the printing.
2649 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2650 if (!isa<UndefValue>(IV)) {
2651 Out << std::string(Indent, ' ');
Bill Wendling145aad02007-02-23 22:45:08 +00002652 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
John Criswell57bbfce2004-10-20 14:38:39 +00002653 writeOperand(IV);
2654 Out << "; /* for PHI node */\n";
2655 }
2656 }
2657}
2658
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002659void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00002660 unsigned Indent) {
Chris Lattnercb3ad012004-05-09 20:41:32 +00002661 if (isGotoCodeNecessary(CurBB, Succ)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00002662 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002663 writeOperand(Succ);
2664 Out << ";\n";
2665 }
2666}
2667
Misha Brukman37f92e22003-09-11 22:34:13 +00002668// Branch instruction printing - Avoid printing out a branch to a basic block
2669// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002670//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002671void CWriter::visitBranchInst(BranchInst &I) {
Chris Lattnera05e0ec2004-05-09 03:42:48 +00002672
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002673 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002674 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002675 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002676 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002677 Out << ") {\n";
Misha Brukmand6a29a52005-04-20 16:05:03 +00002678
John Criswell57bbfce2004-10-20 14:38:39 +00002679 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002680 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Misha Brukmand6a29a52005-04-20 16:05:03 +00002681
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00002682 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002683 Out << " } else {\n";
John Criswell57bbfce2004-10-20 14:38:39 +00002684 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002685 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002686 }
2687 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00002688 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002689 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002690 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002691 Out << ") {\n";
2692
John Criswell57bbfce2004-10-20 14:38:39 +00002693 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002694 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002695 }
2696
2697 Out << " }\n";
2698 } else {
John Criswell57bbfce2004-10-20 14:38:39 +00002699 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002700 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002701 }
2702 Out << "\n";
2703}
2704
Chris Lattner84e66652003-05-03 07:11:00 +00002705// PHI nodes get copied into temporary values at the end of predecessor basic
2706// blocks. We now need to copy these temporary values into the REAL value for
2707// the PHI.
2708void CWriter::visitPHINode(PHINode &I) {
2709 writeOperand(&I);
2710 Out << "__PHI_TEMPORARY";
2711}
2712
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002713
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002714void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002715 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00002716 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00002717
2718 // We must cast the results of binary operations which might be promoted.
2719 bool needsCast = false;
Owen Anderson1d0be152009-08-13 21:58:54 +00002720 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2721 (I.getType() == Type::getInt16Ty(I.getContext()))
2722 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Brian Gaeke031a1122003-06-23 20:00:51 +00002723 needsCast = true;
2724 Out << "((";
Reid Spencer251f2142007-01-09 17:09:09 +00002725 printType(Out, I.getType(), false);
Brian Gaeke031a1122003-06-23 20:00:51 +00002726 Out << ")(";
2727 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002728
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002729 // If this is a negation operation, print it out as such. For FP, we don't
2730 // want to print "-0.0 - X".
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002731 if (BinaryOperator::isNeg(&I)) {
John Criswellce4e1e42005-07-14 19:41:16 +00002732 Out << "-(";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002733 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
John Criswellce4e1e42005-07-14 19:41:16 +00002734 Out << ")";
Owen Andersonfa82b6e2009-07-13 22:18:28 +00002735 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002736 Out << "-(";
2737 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2738 Out << ")";
Reid Spencer0a783f72006-11-02 01:53:59 +00002739 } else if (I.getOpcode() == Instruction::FRem) {
Chris Lattner57da2522005-08-23 20:22:50 +00002740 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson1d0be152009-08-13 21:58:54 +00002741 if (I.getType() == Type::getFloatTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002742 Out << "fmodf(";
Owen Anderson1d0be152009-08-13 21:58:54 +00002743 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Chris Lattner57da2522005-08-23 20:22:50 +00002744 Out << "fmod(";
Dale Johannesen53f0bc12007-09-17 00:38:27 +00002745 else // all 3 flavors of long double
2746 Out << "fmodl(";
Chris Lattner57da2522005-08-23 20:22:50 +00002747 writeOperand(I.getOperand(0));
2748 Out << ", ";
2749 writeOperand(I.getOperand(1));
2750 Out << ")";
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002751 } else {
Reid Spencer1628cec2006-10-26 06:15:43 +00002752
2753 // Write out the cast of the instruction's value back to the proper type
2754 // if necessary.
2755 bool NeedsClosingParens = writeInstructionCast(I);
2756
2757 // Certain instructions require the operand to be forced to a specific type
2758 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2759 // below for operand 1
2760 writeOperandWithCast(I.getOperand(0), I.getOpcode());
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002761
2762 switch (I.getOpcode()) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002763 case Instruction::Add:
2764 case Instruction::FAdd: Out << " + "; break;
2765 case Instruction::Sub:
2766 case Instruction::FSub: Out << " - "; break;
2767 case Instruction::Mul:
2768 case Instruction::FMul: Out << " * "; break;
Reid Spencer0a783f72006-11-02 01:53:59 +00002769 case Instruction::URem:
2770 case Instruction::SRem:
Reid Spencer832254e2007-02-02 02:16:23 +00002771 case Instruction::FRem: Out << " % "; break;
Reid Spencer1628cec2006-10-26 06:15:43 +00002772 case Instruction::UDiv:
2773 case Instruction::SDiv:
Reid Spencer832254e2007-02-02 02:16:23 +00002774 case Instruction::FDiv: Out << " / "; break;
2775 case Instruction::And: Out << " & "; break;
2776 case Instruction::Or: Out << " | "; break;
2777 case Instruction::Xor: Out << " ^ "; break;
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002778 case Instruction::Shl : Out << " << "; break;
Reid Spencer3822ff52006-11-08 06:47:33 +00002779 case Instruction::LShr:
2780 case Instruction::AShr: Out << " >> "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002781 default:
2782#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002783 errs() << "Invalid operator type!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002784#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002785 llvm_unreachable(0);
Chris Lattner6d9b69f2005-03-03 21:12:04 +00002786 }
2787
Reid Spencer1628cec2006-10-26 06:15:43 +00002788 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2789 if (NeedsClosingParens)
2790 Out << "))";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002791 }
2792
Brian Gaeke031a1122003-06-23 20:00:51 +00002793 if (needsCast) {
2794 Out << "))";
2795 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002796}
2797
Reid Spencere4d87aa2006-12-23 06:05:41 +00002798void CWriter::visitICmpInst(ICmpInst &I) {
2799 // We must cast the results of icmp which might be promoted.
2800 bool needsCast = false;
2801
2802 // Write out the cast of the instruction's value back to the proper type
2803 // if necessary.
2804 bool NeedsClosingParens = writeInstructionCast(I);
2805
2806 // Certain icmp predicate require the operand to be forced to a specific type
2807 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2808 // below for operand 1
Chris Lattner5bda9e42007-09-15 06:51:03 +00002809 writeOperandWithCast(I.getOperand(0), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002810
2811 switch (I.getPredicate()) {
2812 case ICmpInst::ICMP_EQ: Out << " == "; break;
2813 case ICmpInst::ICMP_NE: Out << " != "; break;
2814 case ICmpInst::ICMP_ULE:
2815 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2816 case ICmpInst::ICMP_UGE:
2817 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2818 case ICmpInst::ICMP_ULT:
2819 case ICmpInst::ICMP_SLT: Out << " < "; break;
2820 case ICmpInst::ICMP_UGT:
2821 case ICmpInst::ICMP_SGT: Out << " > "; break;
Torok Edwindac237e2009-07-08 20:53:28 +00002822 default:
2823#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002824 errs() << "Invalid icmp predicate!" << I;
Torok Edwindac237e2009-07-08 20:53:28 +00002825#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00002826 llvm_unreachable(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002827 }
2828
Chris Lattner5bda9e42007-09-15 06:51:03 +00002829 writeOperandWithCast(I.getOperand(1), I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002830 if (NeedsClosingParens)
2831 Out << "))";
2832
2833 if (needsCast) {
2834 Out << "))";
2835 }
2836}
2837
2838void CWriter::visitFCmpInst(FCmpInst &I) {
Reid Spencerb801a272007-01-08 06:58:32 +00002839 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2840 Out << "0";
2841 return;
2842 }
2843 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2844 Out << "1";
2845 return;
2846 }
2847
2848 const char* op = 0;
2849 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002850 default: llvm_unreachable("Illegal FCmp predicate");
Reid Spencerb801a272007-01-08 06:58:32 +00002851 case FCmpInst::FCMP_ORD: op = "ord"; break;
2852 case FCmpInst::FCMP_UNO: op = "uno"; break;
2853 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2854 case FCmpInst::FCMP_UNE: op = "une"; break;
2855 case FCmpInst::FCMP_ULT: op = "ult"; break;
2856 case FCmpInst::FCMP_ULE: op = "ule"; break;
2857 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2858 case FCmpInst::FCMP_UGE: op = "uge"; break;
2859 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2860 case FCmpInst::FCMP_ONE: op = "one"; break;
2861 case FCmpInst::FCMP_OLT: op = "olt"; break;
2862 case FCmpInst::FCMP_OLE: op = "ole"; break;
2863 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2864 case FCmpInst::FCMP_OGE: op = "oge"; break;
2865 }
2866
2867 Out << "llvm_fcmp_" << op << "(";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002868 // Write the first operand
2869 writeOperand(I.getOperand(0));
Reid Spencerb801a272007-01-08 06:58:32 +00002870 Out << ", ";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002871 // Write the second operand
2872 writeOperand(I.getOperand(1));
Reid Spencerb801a272007-01-08 06:58:32 +00002873 Out << ")";
Reid Spencere4d87aa2006-12-23 06:05:41 +00002874}
2875
Reid Spencer555a0b12006-12-11 20:39:15 +00002876static const char * getFloatBitCastField(const Type *Ty) {
2877 switch (Ty->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002878 default: llvm_unreachable("Invalid Type");
Reid Spencer47857812006-12-31 05:55:36 +00002879 case Type::FloatTyID: return "Float";
Reid Spencer47857812006-12-31 05:55:36 +00002880 case Type::DoubleTyID: return "Double";
Reid Spencera54b7cb2007-01-12 07:05:14 +00002881 case Type::IntegerTyID: {
2882 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2883 if (NumBits <= 32)
2884 return "Int32";
2885 else
2886 return "Int64";
2887 }
Reid Spencer555a0b12006-12-11 20:39:15 +00002888 }
2889}
2890
Chris Lattnerbb03efd2002-06-25 15:57:03 +00002891void CWriter::visitCastInst(CastInst &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002892 const Type *DstTy = I.getType();
2893 const Type *SrcTy = I.getOperand(0)->getType();
Reid Spencer22586642006-12-17 20:24:50 +00002894 if (isFPIntBitCast(I)) {
Chris Lattnere56d9462008-05-31 09:23:55 +00002895 Out << '(';
Reid Spencer555a0b12006-12-11 20:39:15 +00002896 // These int<->float and long<->double casts need to be handled specially
Bill Wendling145aad02007-02-23 22:45:08 +00002897 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002898 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2899 writeOperand(I.getOperand(0));
Bill Wendling145aad02007-02-23 22:45:08 +00002900 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
Reid Spencer555a0b12006-12-11 20:39:15 +00002901 << getFloatBitCastField(I.getType());
Chris Lattnere56d9462008-05-31 09:23:55 +00002902 Out << ')';
2903 return;
2904 }
2905
2906 Out << '(';
2907 printCast(I.getOpcode(), SrcTy, DstTy);
2908
2909 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson1d0be152009-08-13 21:58:54 +00002910 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2911 I.getOpcode() == Instruction::SExt)
Chris Lattnere56d9462008-05-31 09:23:55 +00002912 Out << "0-";
2913
2914 writeOperand(I.getOperand(0));
2915
Owen Anderson1d0be152009-08-13 21:58:54 +00002916 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnere56d9462008-05-31 09:23:55 +00002917 (I.getOpcode() == Instruction::Trunc ||
2918 I.getOpcode() == Instruction::FPToUI ||
2919 I.getOpcode() == Instruction::FPToSI ||
2920 I.getOpcode() == Instruction::PtrToInt)) {
2921 // Make sure we really get a trunc to bool by anding the operand with 1
2922 Out << "&1u";
Reid Spencer3da59db2006-11-27 01:05:10 +00002923 }
Chris Lattner72623362007-05-03 02:57:13 +00002924 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00002925}
2926
Chris Lattner9f24a072004-03-12 05:52:14 +00002927void CWriter::visitSelectInst(SelectInst &I) {
2928 Out << "((";
2929 writeOperand(I.getCondition());
2930 Out << ") ? (";
2931 writeOperand(I.getTrueValue());
2932 Out << ") : (";
2933 writeOperand(I.getFalseValue());
Misha Brukmand6a29a52005-04-20 16:05:03 +00002934 Out << "))";
Chris Lattner9f24a072004-03-12 05:52:14 +00002935}
2936
2937
Chris Lattnerc2421432004-05-09 04:30:20 +00002938void CWriter::lowerIntrinsics(Function &F) {
Reid Spencer69f80a62007-04-12 21:00:45 +00002939 // This is used to keep track of intrinsics that get generated to a lowered
2940 // function. We must generate the prototypes before the function body which
2941 // will only be expanded on first use (by the loop below).
2942 std::vector<Function*> prototypesToGen;
2943
2944 // Examine all the instructions in this function to find the intrinsics that
2945 // need to be lowered.
Jeff Cohen614408d2007-04-13 22:52:03 +00002946 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
Chris Lattnerc2421432004-05-09 04:30:20 +00002947 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2948 if (CallInst *CI = dyn_cast<CallInst>(I++))
2949 if (Function *F = CI->getCalledFunction())
2950 switch (F->getIntrinsicID()) {
2951 case Intrinsic::not_intrinsic:
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00002952 case Intrinsic::memory_barrier:
Chris Lattnerc2421432004-05-09 04:30:20 +00002953 case Intrinsic::vastart:
2954 case Intrinsic::vacopy:
2955 case Intrinsic::vaend:
2956 case Intrinsic::returnaddress:
2957 case Intrinsic::frameaddress:
2958 case Intrinsic::setjmp:
2959 case Intrinsic::longjmp:
Chris Lattner33e9d292005-02-28 19:29:46 +00002960 case Intrinsic::prefetch:
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00002961 case Intrinsic::powi:
Chris Lattner4e220122008-03-02 08:47:13 +00002962 case Intrinsic::x86_sse_cmp_ss:
2963 case Intrinsic::x86_sse_cmp_ps:
2964 case Intrinsic::x86_sse2_cmp_sd:
2965 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattnerff939212008-03-02 08:54:27 +00002966 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner4e220122008-03-02 08:47:13 +00002967 // We directly implement these intrinsics
Chris Lattnerc2421432004-05-09 04:30:20 +00002968 break;
2969 default:
Chris Lattner87242152006-03-13 23:09:05 +00002970 // If this is an intrinsic that directly corresponds to a GCC
2971 // builtin, we handle it.
2972 const char *BuiltinName = "";
2973#define GET_GCC_BUILTIN_NAME
2974#include "llvm/Intrinsics.gen"
2975#undef GET_GCC_BUILTIN_NAME
2976 // If we handle it, don't lower it.
2977 if (BuiltinName[0]) break;
2978
Chris Lattnerc2421432004-05-09 04:30:20 +00002979 // All other intrinsic calls we must lower.
Chris Lattner67c2d182005-03-18 16:12:37 +00002980 Instruction *Before = 0;
Misha Brukmand6a29a52005-04-20 16:05:03 +00002981 if (CI != &BB->front())
Chris Lattner67c2d182005-03-18 16:12:37 +00002982 Before = prior(BasicBlock::iterator(CI));
Misha Brukmand6a29a52005-04-20 16:05:03 +00002983
Reid Spencer519e2392007-01-29 17:51:02 +00002984 IL->LowerIntrinsicCall(CI);
Chris Lattnerc2421432004-05-09 04:30:20 +00002985 if (Before) { // Move iterator to instruction after call
2986 I = Before; ++I;
2987 } else {
2988 I = BB->begin();
Chris Lattner4ef51372004-02-14 00:31:10 +00002989 }
Reid Spencer69f80a62007-04-12 21:00:45 +00002990 // If the intrinsic got lowered to another call, and that call has
2991 // a definition then we need to make sure its prototype is emitted
2992 // before any calls to it.
2993 if (CallInst *Call = dyn_cast<CallInst>(I))
2994 if (Function *NewF = Call->getCalledFunction())
2995 if (!NewF->isDeclaration())
2996 prototypesToGen.push_back(NewF);
2997
Chris Lattner87242152006-03-13 23:09:05 +00002998 break;
Chris Lattnerc2421432004-05-09 04:30:20 +00002999 }
Chris Lattner4ef51372004-02-14 00:31:10 +00003000
Reid Spencer69f80a62007-04-12 21:00:45 +00003001 // We may have collected some prototypes to emit in the loop above.
3002 // Emit them now, before the function that uses them is emitted. But,
3003 // be careful not to emit them twice.
3004 std::vector<Function*>::iterator I = prototypesToGen.begin();
3005 std::vector<Function*>::iterator E = prototypesToGen.end();
3006 for ( ; I != E; ++I) {
Reid Spencer57c5b182007-04-12 21:57:15 +00003007 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
Reid Spencer69f80a62007-04-12 21:00:45 +00003008 Out << '\n';
3009 printFunctionSignature(*I, true);
3010 Out << ";\n";
Reid Spencer69f80a62007-04-12 21:00:45 +00003011 }
3012 }
3013}
Chris Lattner4ef51372004-02-14 00:31:10 +00003014
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003015void CWriter::visitCallInst(CallInst &I) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003016 if (isa<InlineAsm>(I.getOperand(0)))
3017 return visitInlineAsm(I);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003018
Chris Lattner87242152006-03-13 23:09:05 +00003019 bool WroteCallee = false;
3020
Chris Lattner18ac3c82003-05-08 18:41:45 +00003021 // Handle intrinsic function calls first...
3022 if (Function *F = I.getCalledFunction())
Chris Lattner2299fec2008-03-02 08:29:41 +00003023 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3024 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharthd497d9f2008-02-16 14:46:26 +00003025 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00003026
Chris Lattner4394d512004-11-13 22:21:56 +00003027 Value *Callee = I.getCalledValue();
Misha Brukmand6a29a52005-04-20 16:05:03 +00003028
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003029 const PointerType *PTy = cast<PointerType>(Callee->getType());
3030 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3031
Chris Lattner0c54d892006-05-23 23:39:48 +00003032 // If this is a call to a struct-return function, assign to the first
3033 // parameter instead of passing it to the call.
Devang Patel05988662008-09-25 21:00:45 +00003034 const AttrListPtr &PAL = I.getAttributes();
Evan Cheng7723ab32008-01-12 18:53:07 +00003035 bool hasByVal = I.hasByValArgument();
Devang Patel41e23972008-03-03 21:46:28 +00003036 bool isStructRet = I.hasStructRetAttr();
Chris Lattner0c54d892006-05-23 23:39:48 +00003037 if (isStructRet) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003038 writeOperandDeref(I.getOperand(1));
Evan Cheng3d794782008-01-11 23:10:11 +00003039 Out << " = ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003040 }
3041
Chris Lattnerfe673d92005-05-06 06:53:07 +00003042 if (I.isTailCall()) Out << " /*tail*/ ";
Chris Lattner0c54d892006-05-23 23:39:48 +00003043
3044 if (!WroteCallee) {
3045 // If this is an indirect call to a struct return function, we need to cast
Evan Cheng7723ab32008-01-12 18:53:07 +00003046 // the pointer. Ditto for indirect calls with byval arguments.
3047 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Misha Brukmand6a29a52005-04-20 16:05:03 +00003048
Chris Lattner0c54d892006-05-23 23:39:48 +00003049 // GCC is a real PITA. It does not permit codegening casts of functions to
3050 // function pointers if they are in a call (it generates a trap instruction
3051 // instead!). We work around this by inserting a cast to void* in between
3052 // the function and the function pointer cast. Unfortunately, we can't just
3053 // form the constant expression here, because the folder will immediately
3054 // nuke it.
3055 //
3056 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3057 // that void* and function pointers have the same size. :( To deal with this
3058 // in the common case, we handle casts where the number of arguments passed
3059 // match exactly.
3060 //
3061 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
Reid Spencer3da59db2006-11-27 01:05:10 +00003062 if (CE->isCast())
Chris Lattner0c54d892006-05-23 23:39:48 +00003063 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3064 NeedsCast = true;
3065 Callee = RF;
3066 }
3067
3068 if (NeedsCast) {
3069 // Ok, just cast the pointer type.
3070 Out << "((";
Evan Cheng7723ab32008-01-12 18:53:07 +00003071 if (isStructRet)
Duncan Sandsdc024672007-11-27 13:23:08 +00003072 printStructReturnPointerFunctionType(Out, PAL,
Chris Lattner0c54d892006-05-23 23:39:48 +00003073 cast<PointerType>(I.getCalledValue()->getType()));
Evan Cheng7723ab32008-01-12 18:53:07 +00003074 else if (hasByVal)
3075 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3076 else
3077 printType(Out, I.getCalledValue()->getType());
Chris Lattner0c54d892006-05-23 23:39:48 +00003078 Out << ")(void*)";
3079 }
3080 writeOperand(Callee);
3081 if (NeedsCast) Out << ')';
3082 }
3083
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003084 Out << '(';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003085
Chris Lattner4394d512004-11-13 22:21:56 +00003086 unsigned NumDeclaredParams = FTy->getNumParams();
3087
Chris Lattner0c54d892006-05-23 23:39:48 +00003088 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3089 unsigned ArgNo = 0;
3090 if (isStructRet) { // Skip struct return argument.
3091 ++AI;
3092 ++ArgNo;
3093 }
3094
3095 bool PrintedArg = false;
Evan Cheng3d794782008-01-11 23:10:11 +00003096 for (; AI != AE; ++AI, ++ArgNo) {
Chris Lattner0c54d892006-05-23 23:39:48 +00003097 if (PrintedArg) Out << ", ";
3098 if (ArgNo < NumDeclaredParams &&
3099 (*AI)->getType() != FTy->getParamType(ArgNo)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003100 Out << '(';
Reid Spencer0ae96932007-01-07 03:24:48 +00003101 printType(Out, FTy->getParamType(ArgNo),
Devang Patel05988662008-09-25 21:00:45 +00003102 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003103 Out << ')';
Chris Lattner4394d512004-11-13 22:21:56 +00003104 }
Evan Cheng3d794782008-01-11 23:10:11 +00003105 // Check if the argument is expected to be passed by value.
Devang Patel05988662008-09-25 21:00:45 +00003106 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattnere05252b42008-03-02 08:07:24 +00003107 writeOperandDeref(*AI);
3108 else
3109 writeOperand(*AI);
Chris Lattner0c54d892006-05-23 23:39:48 +00003110 PrintedArg = true;
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003111 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003112 Out << ')';
Misha Brukmand6a29a52005-04-20 16:05:03 +00003113}
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003114
Chris Lattner2299fec2008-03-02 08:29:41 +00003115/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3116/// if the entire call is handled, return false it it wasn't handled, and
3117/// optionally set 'WroteCallee' if the callee has already been printed out.
3118bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3119 bool &WroteCallee) {
3120 switch (ID) {
3121 default: {
3122 // If this is an intrinsic that directly corresponds to a GCC
3123 // builtin, we emit it here.
3124 const char *BuiltinName = "";
3125 Function *F = I.getCalledFunction();
3126#define GET_GCC_BUILTIN_NAME
3127#include "llvm/Intrinsics.gen"
3128#undef GET_GCC_BUILTIN_NAME
3129 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3130
3131 Out << BuiltinName;
3132 WroteCallee = true;
3133 return false;
3134 }
3135 case Intrinsic::memory_barrier:
Andrew Lenharth6ad150b2008-03-05 23:41:37 +00003136 Out << "__sync_synchronize()";
Chris Lattner2299fec2008-03-02 08:29:41 +00003137 return true;
3138 case Intrinsic::vastart:
3139 Out << "0; ";
3140
3141 Out << "va_start(*(va_list*)";
3142 writeOperand(I.getOperand(1));
3143 Out << ", ";
3144 // Output the last argument to the enclosing function.
3145 if (I.getParent()->getParent()->arg_empty()) {
Torok Edwindac237e2009-07-08 20:53:28 +00003146 std::string msg;
3147 raw_string_ostream Msg(msg);
3148 Msg << "The C backend does not currently support zero "
Chris Lattner2299fec2008-03-02 08:29:41 +00003149 << "argument varargs functions, such as '"
Torok Edwindac237e2009-07-08 20:53:28 +00003150 << I.getParent()->getParent()->getName() << "'!";
3151 llvm_report_error(Msg.str());
Chris Lattner2299fec2008-03-02 08:29:41 +00003152 }
3153 writeOperand(--I.getParent()->getParent()->arg_end());
3154 Out << ')';
3155 return true;
3156 case Intrinsic::vaend:
3157 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3158 Out << "0; va_end(*(va_list*)";
3159 writeOperand(I.getOperand(1));
3160 Out << ')';
3161 } else {
3162 Out << "va_end(*(va_list*)0)";
3163 }
3164 return true;
3165 case Intrinsic::vacopy:
3166 Out << "0; ";
3167 Out << "va_copy(*(va_list*)";
3168 writeOperand(I.getOperand(1));
3169 Out << ", *(va_list*)";
3170 writeOperand(I.getOperand(2));
3171 Out << ')';
3172 return true;
3173 case Intrinsic::returnaddress:
3174 Out << "__builtin_return_address(";
3175 writeOperand(I.getOperand(1));
3176 Out << ')';
3177 return true;
3178 case Intrinsic::frameaddress:
3179 Out << "__builtin_frame_address(";
3180 writeOperand(I.getOperand(1));
3181 Out << ')';
3182 return true;
3183 case Intrinsic::powi:
3184 Out << "__builtin_powi(";
3185 writeOperand(I.getOperand(1));
3186 Out << ", ";
3187 writeOperand(I.getOperand(2));
3188 Out << ')';
3189 return true;
3190 case Intrinsic::setjmp:
3191 Out << "setjmp(*(jmp_buf*)";
3192 writeOperand(I.getOperand(1));
3193 Out << ')';
3194 return true;
3195 case Intrinsic::longjmp:
3196 Out << "longjmp(*(jmp_buf*)";
3197 writeOperand(I.getOperand(1));
3198 Out << ", ";
3199 writeOperand(I.getOperand(2));
3200 Out << ')';
3201 return true;
3202 case Intrinsic::prefetch:
3203 Out << "LLVM_PREFETCH((const void *)";
3204 writeOperand(I.getOperand(1));
3205 Out << ", ";
3206 writeOperand(I.getOperand(2));
3207 Out << ", ";
3208 writeOperand(I.getOperand(3));
3209 Out << ")";
3210 return true;
3211 case Intrinsic::stacksave:
3212 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3213 // to work around GCC bugs (see PR1809).
3214 Out << "0; *((void**)&" << GetValueName(&I)
3215 << ") = __builtin_stack_save()";
3216 return true;
Chris Lattner4e220122008-03-02 08:47:13 +00003217 case Intrinsic::x86_sse_cmp_ss:
3218 case Intrinsic::x86_sse_cmp_ps:
3219 case Intrinsic::x86_sse2_cmp_sd:
3220 case Intrinsic::x86_sse2_cmp_pd:
3221 Out << '(';
3222 printType(Out, I.getType());
3223 Out << ')';
3224 // Multiple GCC builtins multiplex onto this intrinsic.
3225 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003226 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner4e220122008-03-02 08:47:13 +00003227 case 0: Out << "__builtin_ia32_cmpeq"; break;
3228 case 1: Out << "__builtin_ia32_cmplt"; break;
3229 case 2: Out << "__builtin_ia32_cmple"; break;
3230 case 3: Out << "__builtin_ia32_cmpunord"; break;
3231 case 4: Out << "__builtin_ia32_cmpneq"; break;
3232 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3233 case 6: Out << "__builtin_ia32_cmpnle"; break;
3234 case 7: Out << "__builtin_ia32_cmpord"; break;
3235 }
3236 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3237 Out << 'p';
3238 else
3239 Out << 's';
3240 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3241 Out << 's';
3242 else
3243 Out << 'd';
3244
3245 Out << "(";
3246 writeOperand(I.getOperand(1));
3247 Out << ", ";
3248 writeOperand(I.getOperand(2));
3249 Out << ")";
3250 return true;
Chris Lattnerff939212008-03-02 08:54:27 +00003251 case Intrinsic::ppc_altivec_lvsl:
3252 Out << '(';
3253 printType(Out, I.getType());
3254 Out << ')';
3255 Out << "__builtin_altivec_lvsl(0, (void*)";
3256 writeOperand(I.getOperand(1));
3257 Out << ")";
3258 return true;
Chris Lattner2299fec2008-03-02 08:29:41 +00003259 }
3260}
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003261
3262//This converts the llvm constraint string to something gcc is expecting.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003263//TODO: work out platform independent constraints and factor those out
Andrew Lenharth238581f2006-11-28 19:56:02 +00003264// of the per target tables
3265// handle multiple constraint codes
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003266std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003267 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3268
Chris Lattneraf76e592009-08-22 20:48:53 +00003269 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003270 const MCAsmInfo *TargetAsm;
3271 std::string Triple = TheModule->getTargetTriple();
3272 if (Triple.empty())
3273 Triple = llvm::sys::getHostTriple();
3274
3275 std::string E;
3276 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3277 TargetAsm = Match->createAsmInfo(Triple);
3278 else
3279 return c.Codes[0];
3280
3281 const char *const *table = TargetAsm->getAsmCBE();
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003282
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003283 // Search the translation table if it exists.
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003284 for (int i = 0; table && table[i]; i += 2)
Chris Lattnerc0dba722010-01-17 18:22:35 +00003285 if (c.Codes[0] == table[i]) {
3286 delete TargetAsm;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003287 return table[i+1];
Chris Lattnerc0dba722010-01-17 18:22:35 +00003288 }
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003289
Daniel Dunbar51b198a2009-07-15 20:24:03 +00003290 // Default is identity.
Chris Lattnerc0dba722010-01-17 18:22:35 +00003291 delete TargetAsm;
Andrew Lenharth85f22282006-11-28 22:25:32 +00003292 return c.Codes[0];
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003293}
3294
3295//TODO: import logic from AsmPrinter.cpp
Andrew Lenharthe0cf0752006-11-28 19:53:36 +00003296static std::string gccifyAsm(std::string asmstr) {
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003297 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3298 if (asmstr[i] == '\n')
3299 asmstr.replace(i, 1, "\\n");
3300 else if (asmstr[i] == '\t')
3301 asmstr.replace(i, 1, "\\t");
3302 else if (asmstr[i] == '$') {
3303 if (asmstr[i + 1] == '{') {
3304 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3305 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3306 std::string n = "%" +
3307 asmstr.substr(a + 1, b - a - 1) +
3308 asmstr.substr(i + 2, a - i - 2);
3309 asmstr.replace(i, b - i + 1, n);
3310 i += n.size() - 1;
3311 } else
3312 asmstr.replace(i, 1, "%");
3313 }
3314 else if (asmstr[i] == '%')//grr
3315 { asmstr.replace(i, 1, "%%"); ++i;}
3316
3317 return asmstr;
3318}
3319
Andrew Lenharth238581f2006-11-28 19:56:02 +00003320//TODO: assumptions about what consume arguments from the call are likely wrong
3321// handle communitivity
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003322void CWriter::visitInlineAsm(CallInst &CI) {
3323 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003324 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003325
3326 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00003327 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003328 ;
3329 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3330 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3331 ResultVals.push_back(std::make_pair(&CI, (int)i));
3332 } else {
3333 ResultVals.push_back(std::make_pair(&CI, -1));
3334 }
3335
Chris Lattner67f631d2008-06-04 18:03:28 +00003336 // Fix up the asm string for gcc and emit it.
3337 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3338 Out << " :";
3339
3340 unsigned ValueCount = 0;
3341 bool IsFirst = true;
3342
3343 // Convert over all the output constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003344 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattner67f631d2008-06-04 18:03:28 +00003345 E = Constraints.end(); I != E; ++I) {
3346
3347 if (I->Type != InlineAsm::isOutput) {
3348 ++ValueCount;
3349 continue; // Ignore non-output constraints.
3350 }
3351
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003352 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003353 std::string C = InterpretASMConstraint(*I);
3354 if (C.empty()) continue;
3355
Chris Lattner67f631d2008-06-04 18:03:28 +00003356 if (!IsFirst) {
Chris Lattnerf6a048c2008-05-22 06:19:37 +00003357 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003358 IsFirst = false;
3359 }
3360
3361 // Unpack the dest.
3362 Value *DestVal;
3363 int DestValNo = -1;
3364
3365 if (ValueCount < ResultVals.size()) {
3366 DestVal = ResultVals[ValueCount].first;
3367 DestValNo = ResultVals[ValueCount].second;
3368 } else
3369 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3370
3371 if (I->isEarlyClobber)
3372 C = "&"+C;
3373
3374 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3375 if (DestValNo != -1)
3376 Out << ".field" << DestValNo; // Multiple retvals.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003377 Out << ")";
Chris Lattner67f631d2008-06-04 18:03:28 +00003378 ++ValueCount;
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003379 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003380
3381
3382 // Convert over all the input constraints.
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003383 Out << "\n :";
Chris Lattner67f631d2008-06-04 18:03:28 +00003384 IsFirst = true;
3385 ValueCount = 0;
3386 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3387 E = Constraints.end(); I != E; ++I) {
3388 if (I->Type != InlineAsm::isInput) {
3389 ++ValueCount;
3390 continue; // Ignore non-input constraints.
3391 }
3392
3393 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3394 std::string C = InterpretASMConstraint(*I);
3395 if (C.empty()) continue;
3396
3397 if (!IsFirst) {
Chris Lattner687a4cb2008-05-22 06:29:38 +00003398 Out << ", ";
Chris Lattner67f631d2008-06-04 18:03:28 +00003399 IsFirst = false;
3400 }
3401
3402 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3403 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3404
3405 Out << "\"" << C << "\"(";
3406 if (!I->isIndirect)
3407 writeOperand(SrcVal);
3408 else
3409 writeOperandDeref(SrcVal);
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003410 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003411 }
Chris Lattner67f631d2008-06-04 18:03:28 +00003412
3413 // Convert over the clobber constraints.
3414 IsFirst = true;
Chris Lattner67f631d2008-06-04 18:03:28 +00003415 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3416 E = Constraints.end(); I != E; ++I) {
3417 if (I->Type != InlineAsm::isClobber)
3418 continue; // Ignore non-input constraints.
3419
3420 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3421 std::string C = InterpretASMConstraint(*I);
3422 if (C.empty()) continue;
3423
3424 if (!IsFirst) {
3425 Out << ", ";
3426 IsFirst = false;
3427 }
3428
3429 Out << '\"' << C << '"';
3430 }
3431
Andrew Lenharthf45148e2006-11-28 23:07:32 +00003432 Out << ")";
Andrew Lenharth29c277f2006-11-27 23:50:49 +00003433}
3434
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003435void CWriter::visitAllocaInst(AllocaInst &I) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003436 Out << '(';
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003437 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003438 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00003439 printType(Out, I.getType()->getElementType());
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003440 Out << ')';
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003441 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003442 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003443 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003444 }
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003445 Out << ')';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003446}
3447
Chris Lattnere05252b42008-03-02 08:07:24 +00003448void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohman9f8d5712008-07-24 17:57:48 +00003449 gep_type_iterator E, bool Static) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003450
3451 // If there are no indices, just print out the pointer.
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003452 if (I == E) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003453 writeOperand(Ptr);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00003454 return;
3455 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003456
3457 // Find out if the last index is into a vector. If so, we have to print this
3458 // specially. Since vectors can't have elements of indexable type, only the
3459 // last index could possibly be of a vector element.
3460 const VectorType *LastIndexIsVector = 0;
3461 {
3462 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3463 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003464 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003465
3466 Out << "(";
3467
3468 // If the last index is into a vector, we can't print it as &a[i][j] because
3469 // we can't index into a vector with j in GCC. Instead, emit this as
3470 // (((float*)&a[i])+j)
3471 if (LastIndexIsVector) {
3472 Out << "((";
3473 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3474 Out << ")(";
3475 }
3476
3477 Out << '&';
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003478
Chris Lattnere05252b42008-03-02 08:07:24 +00003479 // If the first index is 0 (very typical) we can do a number of
3480 // simplifications to clean up the code.
3481 Value *FirstOp = I.getOperand();
3482 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3483 // First index isn't simple, print it the hard way.
3484 writeOperand(Ptr);
3485 } else {
3486 ++I; // Skip the zero index.
Nick Hildenbrandte548f002002-09-25 20:29:26 +00003487
Chris Lattnere05252b42008-03-02 08:07:24 +00003488 // Okay, emit the first operand. If Ptr is something that is already address
3489 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3490 if (isAddressExposed(Ptr)) {
Dan Gohman9f8d5712008-07-24 17:57:48 +00003491 writeOperandInternal(Ptr, Static);
Chris Lattnere05252b42008-03-02 08:07:24 +00003492 } else if (I != E && isa<StructType>(*I)) {
3493 // If we didn't already emit the first operand, see if we can print it as
3494 // P->f instead of "P[0].f"
3495 writeOperand(Ptr);
3496 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3497 ++I; // eat the struct index as well.
3498 } else {
3499 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3500 Out << "(*";
3501 writeOperand(Ptr);
3502 Out << ")";
Chris Lattner23e90702003-11-25 20:49:55 +00003503 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003504 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00003505
Chris Lattnere05252b42008-03-02 08:07:24 +00003506 for (; I != E; ++I) {
Chris Lattner23e90702003-11-25 20:49:55 +00003507 if (isa<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003508 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman193c2352008-06-02 21:30:49 +00003509 } else if (isa<ArrayType>(*I)) {
3510 Out << ".array[";
3511 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3512 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003513 } else if (!isa<VectorType>(*I)) {
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003514 Out << '[';
Chris Lattner96b207c2007-09-22 20:16:48 +00003515 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Misha Brukmanb70aaa62005-02-14 18:52:35 +00003516 Out << ']';
Chris Lattnere05252b42008-03-02 08:07:24 +00003517 } else {
3518 // If the last index is into a vector, then print it out as "+j)". This
3519 // works with the 'LastIndexIsVector' code above.
3520 if (isa<Constant>(I.getOperand()) &&
3521 cast<Constant>(I.getOperand())->isNullValue()) {
3522 Out << "))"; // avoid "+0".
3523 } else {
3524 Out << ")+(";
3525 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3526 Out << "))";
3527 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003528 }
Chris Lattnere05252b42008-03-02 08:07:24 +00003529 }
3530 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003531}
3532
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003533void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3534 bool IsVolatile, unsigned Alignment) {
3535
3536 bool IsUnaligned = Alignment &&
3537 Alignment < TD->getABITypeAlignment(OperandType);
3538
3539 if (!IsUnaligned)
3540 Out << '*';
3541 if (IsVolatile || IsUnaligned) {
Chris Lattner8399e022005-02-15 05:52:14 +00003542 Out << "((";
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003543 if (IsUnaligned)
3544 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3545 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3546 if (IsUnaligned) {
3547 Out << "; } ";
3548 if (IsVolatile) Out << "volatile ";
3549 Out << "*";
3550 }
Chris Lattnerb94388a2005-09-27 20:52:44 +00003551 Out << ")";
Chris Lattner9d30e222005-02-14 16:47:52 +00003552 }
3553
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003554 writeOperand(Operand);
Chris Lattner9d30e222005-02-14 16:47:52 +00003555
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003556 if (IsVolatile || IsUnaligned) {
Misha Brukman23ba0c52005-03-08 00:26:08 +00003557 Out << ')';
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003558 if (IsUnaligned)
3559 Out << "->data";
3560 }
3561}
3562
3563void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003564 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3565 I.getAlignment());
3566
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003567}
3568
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003569void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio859efca2008-02-01 21:25:59 +00003570 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3571 I.isVolatile(), I.getAlignment());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003572 Out << " = ";
Reid Spencerbdc75082007-03-03 16:33:33 +00003573 Value *Operand = I.getOperand(0);
3574 Constant *BitMask = 0;
3575 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3576 if (!ITy->isPowerOf2ByteWidth())
3577 // We have a bit width that doesn't match an even power-of-2 byte
3578 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneed707b2009-07-24 23:12:02 +00003579 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Reid Spencerbdc75082007-03-03 16:33:33 +00003580 if (BitMask)
3581 Out << "((";
3582 writeOperand(Operand);
3583 if (BitMask) {
3584 Out << ") & ";
Dan Gohman9f8d5712008-07-24 17:57:48 +00003585 printConstant(BitMask, false);
Reid Spencerbdc75082007-03-03 16:33:33 +00003586 Out << ")";
3587 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003588}
3589
Chris Lattnerbb03efd2002-06-25 15:57:03 +00003590void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnere05252b42008-03-02 08:07:24 +00003591 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohman9f8d5712008-07-24 17:57:48 +00003592 gep_type_end(I), false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00003593}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003594
Chris Lattner4d45bd02003-10-18 05:57:43 +00003595void CWriter::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +00003596 Out << "va_arg(*(va_list*)";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003597 writeOperand(I.getOperand(0));
Andrew Lenharth558bc882005-06-18 18:34:52 +00003598 Out << ", ";
Chris Lattner7635ea42003-11-03 01:01:59 +00003599 printType(Out, I.getType());
Andrew Lenharth558bc882005-06-18 18:34:52 +00003600 Out << ");\n ";
Chris Lattner4d45bd02003-10-18 05:57:43 +00003601}
3602
Chris Lattner33a44d92008-03-02 03:52:39 +00003603void CWriter::visitInsertElementInst(InsertElementInst &I) {
3604 const Type *EltTy = I.getType()->getElementType();
3605 writeOperand(I.getOperand(0));
3606 Out << ";\n ";
3607 Out << "((";
3608 printType(Out, PointerType::getUnqual(EltTy));
3609 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattner33a44d92008-03-02 03:52:39 +00003610 writeOperand(I.getOperand(2));
Chris Lattner9152daf2008-03-02 08:10:16 +00003611 Out << "] = (";
3612 writeOperand(I.getOperand(1));
Chris Lattner33a44d92008-03-02 03:52:39 +00003613 Out << ")";
3614}
3615
Chris Lattner0452ed62008-03-02 03:57:08 +00003616void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3617 // We know that our operand is not inlined.
3618 Out << "((";
3619 const Type *EltTy =
3620 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3621 printType(Out, PointerType::getUnqual(EltTy));
3622 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3623 writeOperand(I.getOperand(1));
3624 Out << "]";
3625}
3626
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003627void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3628 Out << "(";
3629 printType(Out, SVI.getType());
3630 Out << "){ ";
3631 const VectorType *VT = SVI.getType();
3632 unsigned NumElts = VT->getNumElements();
3633 const Type *EltTy = VT->getElementType();
3634
3635 for (unsigned i = 0; i != NumElts; ++i) {
3636 if (i) Out << ", ";
3637 int SrcVal = SVI.getMaskValue(i);
3638 if ((unsigned)SrcVal >= NumElts*2) {
3639 Out << " 0/*undef*/ ";
3640 } else {
3641 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3642 if (isa<Instruction>(Op)) {
3643 // Do an extractelement of this value from the appropriate input.
3644 Out << "((";
3645 printType(Out, PointerType::getUnqual(EltTy));
3646 Out << ")(&" << GetValueName(Op)
Duncan Sands43e2a032008-05-27 11:50:51 +00003647 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003648 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3649 Out << "0";
3650 } else {
Duncan Sands43e2a032008-05-27 11:50:51 +00003651 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohman9f8d5712008-07-24 17:57:48 +00003652 (NumElts-1)),
3653 false);
Chris Lattnerb1855ad2008-03-02 05:41:07 +00003654 }
3655 }
3656 }
3657 Out << "}";
3658}
Chris Lattner0452ed62008-03-02 03:57:08 +00003659
Dan Gohman193c2352008-06-02 21:30:49 +00003660void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3661 // Start by copying the entire aggregate value into the result variable.
3662 writeOperand(IVI.getOperand(0));
3663 Out << ";\n ";
3664
3665 // Then do the insert to update the field.
3666 Out << GetValueName(&IVI);
3667 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3668 i != e; ++i) {
3669 const Type *IndexedTy =
3670 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3671 if (isa<ArrayType>(IndexedTy))
3672 Out << ".array[" << *i << "]";
3673 else
3674 Out << ".field" << *i;
3675 }
3676 Out << " = ";
3677 writeOperand(IVI.getOperand(1));
3678}
3679
3680void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3681 Out << "(";
3682 if (isa<UndefValue>(EVI.getOperand(0))) {
3683 Out << "(";
3684 printType(Out, EVI.getType());
3685 Out << ") 0/*UNDEF*/";
3686 } else {
3687 Out << GetValueName(EVI.getOperand(0));
3688 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3689 i != e; ++i) {
3690 const Type *IndexedTy =
3691 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3692 if (isa<ArrayType>(IndexedTy))
3693 Out << ".array[" << *i << "]";
3694 else
3695 Out << ".field" << *i;
3696 }
3697 }
3698 Out << ")";
3699}
3700
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00003701//===----------------------------------------------------------------------===//
3702// External Interface declaration
3703//===----------------------------------------------------------------------===//
3704
Chris Lattner1911fd42006-09-04 04:14:57 +00003705bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00003706 formatted_raw_ostream &o,
Chris Lattner1911fd42006-09-04 04:14:57 +00003707 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00003708 CodeGenOpt::Level OptLevel) {
Chris Lattner0431c962005-06-25 02:48:37 +00003709 if (FileType != TargetMachine::AssemblyFile) return true;
3710
Gordon Henriksence224772008-01-07 01:30:38 +00003711 PM.add(createGCLoweringPass());
Chris Lattner94f4f8e2004-02-13 23:00:29 +00003712 PM.add(createLowerInvokePass());
Chris Lattnerbad13eb2005-11-02 17:42:58 +00003713 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
Chris Lattnerf9a05322006-02-13 22:22:42 +00003714 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
Chris Lattnerbc641b92006-03-23 05:43:16 +00003715 PM.add(new CWriter(o));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003716 PM.add(createGCInfoDeleter());
Chris Lattnerf31182a2004-02-13 23:18:48 +00003717 return false;
3718}