blob: 6a7643a79b6f7536bbe9ff4f18d050611b09b46d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This library converts LLVM code to C code, compilable by GCC and other C
11// compilers.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CTargetMachine.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
20#include "llvm/Instructions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Pass.h"
22#include "llvm/PassManager.h"
23#include "llvm/TypeSymbolTable.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/IntrinsicInst.h"
26#include "llvm/InlineAsm.h"
Daniel Dunbar4baa5fe2009-08-03 04:03:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattnera38b2872010-01-13 06:38:18 +000028#include "llvm/ADT/SmallString.h"
Daniel Dunbar4baa5fe2009-08-03 04:03:51 +000029#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Analysis/ConstantsScanner.h"
31#include "llvm/Analysis/FindUsedTypes.h"
32#include "llvm/Analysis/LoopInfo.h"
Anton Korobeynikov865e6752009-08-05 09:29:56 +000033#include "llvm/Analysis/ValueTracking.h"
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000034#include "llvm/CodeGen/Passes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/CodeGen/IntrinsicLowering.h"
Chris Lattner31a54742010-01-16 21:57:06 +000036#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner621c44d2009-08-22 20:48:53 +000038#include "llvm/MC/MCAsmInfo.h"
Chris Lattner11d7dfa2010-01-13 21:12:34 +000039#include "llvm/MC/MCSymbol.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Target/TargetData.h"
Daniel Dunbarfe5939f2009-07-15 20:24:03 +000041#include "llvm/Target/TargetRegistry.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
Edwin Török4d9756a2009-07-08 20:53:28 +000044#include "llvm/Support/ErrorHandling.h"
David Greene302008d2009-07-14 20:18:05 +000045#include "llvm/Support/FormattedStream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
47#include "llvm/Support/InstVisitor.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/MathExtras.h"
Daniel Dunbar4baa5fe2009-08-03 04:03:51 +000049#include "llvm/System/Host.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050#include "llvm/Config/config.h"
51#include <algorithm>
52#include <sstream>
53using namespace llvm;
54
Daniel Dunbarc680b012009-07-25 06:49:55 +000055extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
Daniel Dunbare6ad1102009-08-04 04:02:45 +000057 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
Daniel Dunbarc680b012009-07-25 06:49:55 +000058}
Douglas Gregor1dc5ff42009-06-16 20:12:29 +000059
Dan Gohman089efff2008-05-13 00:00:25 +000060namespace {
Chris Lattner63ab9bb2010-01-17 18:22:35 +000061 class CBEMCAsmInfo : public MCAsmInfo {
62 public:
63 CBEMCAsmInfo() {
64 GlobalPrefix = "";
65 PrivateGlobalPrefix = "";
66 }
67 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +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.
71 ///
72 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
73 public:
74 static char ID;
75 CBackendNameAllUsedStructsAndMergeFunctions()
Dan Gohman26f8c272008-09-04 17:05:41 +000076 : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
85 virtual bool runOnModule(Module &M);
86 };
87
88 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
89
90 /// 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 Greene302008d2009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 IntrinsicLowering *IL;
95 Mangler *Mang;
96 LoopInfo *LI;
97 const Module *TheModule;
Chris Lattner621c44d2009-08-22 20:48:53 +000098 const MCAsmInfo* TAsm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099 const TargetData* TD;
100 std::map<const Type *, std::string> TypeNames;
101 std::map<const ConstantFP *, unsigned> FPConstantMap;
102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
Chris Lattner8bbc8592008-03-02 08:07:24 +0000103 std::set<const Argument*> ByValParams;
Chris Lattnerf6e12012008-10-22 04:53:16 +0000104 unsigned FPCounter;
Owen Andersonde8a9442009-06-26 19:48:37 +0000105 unsigned OpaqueCounter;
Chris Lattnerb66867f2009-07-13 23:46:46 +0000106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108
109 public:
110 static char ID;
David Greene302008d2009-07-14 20:18:05 +0000111 explicit CWriter(formatted_raw_ostream &o)
Dan Gohman26f8c272008-09-04 17:05:41 +0000112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
Chris Lattnerb66867f2009-07-13 23:46:46 +0000113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
Chris Lattnerf6e12012008-10-22 04:53:16 +0000114 FPCounter = 0;
115 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116
117 virtual const char *getPassName() const { return "C backend"; }
118
119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
122 }
123
124 virtual bool doInitialization(Module &M);
125
126 bool runOnFunction(Function &F) {
Chris Lattner3ed055f2009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 LI = &getAnalysis<LoopInfo>();
133
134 // Get rid of intrinsics we can't handle.
135 lowerIntrinsics(F);
136
137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
139
140 printFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 return false;
142 }
143
144 virtual bool doFinalization(Module &M) {
145 // Free memory...
Nuno Lopes6c857162009-01-13 23:35:49 +0000146 delete IL;
147 delete TD;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 delete Mang;
Evan Cheng17254e62008-01-11 09:12:49 +0000149 FPConstantMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 TypeNames.clear();
Evan Cheng17254e62008-01-11 09:12:49 +0000151 ByValParams.clear();
Chris Lattner8bbc8592008-03-02 08:07:24 +0000152 intrinsicPrototypesAlreadyGenerated.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 return false;
154 }
155
David Greene302008d2009-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 Anderson847b99b2008-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 Pateld222f862008-09-25 21:00:45 +0000166 const AttrListPtr &PAL = AttrListPtr());
David Greene302008d2009-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 Anderson847b99b2008-08-21 00:14:44 +0000171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
172 bool isSigned,
173 const std::string &NameSoFar = "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
David Greene302008d2009-07-14 20:18:05 +0000175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Pateld222f862008-09-25 21:00:45 +0000176 const AttrListPtr &PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 const PointerType *Ty);
Chris Lattner8bbc8592008-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192
Dan Gohmanad831302008-07-24 17:57:48 +0000193 void writeOperand(Value *Operand, bool Static = false);
Chris Lattnerd70f5a82008-05-31 09:23:55 +0000194 void writeInstComputationInline(Instruction &I);
Dan Gohmanad831302008-07-24 17:57:48 +0000195 void writeOperandInternal(Value *Operand, bool Static = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
Chris Lattner389c9142007-09-15 06:51:03 +0000197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 bool writeInstructionCast(const Instruction &I);
199
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +0000200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
202
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 private :
204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
205
206 void lowerIntrinsics(Function &F);
207
208 void printModule(Module *M);
209 void printModuleTypes(const TypeSymbolTable &ST);
Dan Gohman5d995b02008-06-02 21:30:49 +0000210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 void printFloatingPointConstants(Function &F);
Chris Lattnerf6e12012008-10-22 04:53:16 +0000212 void printFloatingPointConstants(const Constant *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 void printFunctionSignature(const Function *F, bool Prototype);
214
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
218
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
Dan Gohmanad831302008-07-24 17:57:48 +0000220 void printConstant(Constant *CPV, bool Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
Dan Gohmanad831302008-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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225
Chris Lattner8bbc8592008-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 //
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
243 if (isa<CmpInst>(I))
244 return true;
245
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
Owen Anderson35b47072009-08-13 21:58:54 +0000248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Dan Gohman5d995b02008-06-02 21:30:49 +0000250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 // Don't inline a load across a store or other bad things!
253 return false;
254
Chris Lattnerf858a042008-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
265 }
266
267 // 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!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
277 return 0;
278 return AI;
279 }
280
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
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
290
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
Chris Lattner4c3800f2009-10-28 00:19:10 +0000294 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 void visitInvokeInst(InvokeInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000296 llvm_unreachable("Lowerinvoke pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 }
298
299 void visitUnwindInst(UnwindInst &I) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000300 llvm_unreachable("Lowerinvoke pass didn't work!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 }
302 void visitUnreachableInst(UnreachableInst &I);
303
304 void visitPHINode(PHINode &I);
305 void visitBinaryOperator(Instruction &I);
306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
308
309 void visitCastInst (CastInst &I);
310 void visitSelectInst(SelectInst &I);
311 void visitCallInst (CallInst &I);
312 void visitInlineAsm(CallInst &I);
Chris Lattnera74b9182008-03-02 08:29:41 +0000313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 void visitAllocaInst(AllocaInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
Chris Lattnerf41a7942008-03-02 03:52:39 +0000320
321 void visitInsertElementInst(InsertElementInst &I);
Chris Lattnera5f0bc02008-03-02 03:57:08 +0000322 void visitExtractElementInst(ExtractElementInst &I);
Chris Lattnerf858a042008-03-02 05:41:07 +0000323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324
Dan Gohman5d995b02008-06-02 21:30:49 +0000325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328 void visitInstruction(Instruction &I) {
Edwin Török4d9756a2009-07-08 20:53:28 +0000329#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000330 errs() << "C Writer does not know about " << I;
Edwin Török4d9756a2009-07-08 20:53:28 +0000331#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000332 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 }
334
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
337 }
338
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
343 unsigned Indent);
Chris Lattner8bbc8592008-03-02 08:07:24 +0000344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohmanad831302008-07-24 17:57:48 +0000345 gep_type_iterator E, bool Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346
347 std::string GetValueName(const Value *Operand);
348 };
349}
350
351char CWriter::ID = 0;
352
Chris Lattnerd2f59b82010-01-13 19:54:07 +0000353
Chris Lattnerd2f59b82010-01-13 19:54:07 +0000354static std::string Mangle(const std::string &S) {
Chris Lattnere295e552010-01-17 19:23:46 +0000355 SmallString<52> Result;
356 Mangler::appendMangledName(Result, S, 0);
357 return std::string(Result.begin(), Result.end());
Chris Lattnerd2f59b82010-01-13 19:54:07 +0000358}
359
360
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361/// This method inserts names for any unnamed structure types that are used by
362/// the program, and removes names from structure types that are not used by the
363/// program.
364///
365bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
366 // Get a set of types that are used by the program...
367 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
368
369 // Loop over the module symbol table, removing types from UT that are
370 // already named, and removing names for types that are not used.
371 //
372 TypeSymbolTable &TST = M.getTypeSymbolTable();
373 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
374 TI != TE; ) {
375 TypeSymbolTable::iterator I = TI++;
376
Dan Gohman5d995b02008-06-02 21:30:49 +0000377 // If this isn't a struct or array type, remove it from our set of types
378 // to name. This simplifies emission later.
379 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
380 !isa<ArrayType>(I->second)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 TST.remove(I);
382 } else {
383 // If this is not used, remove it from the symbol table.
384 std::set<const Type *>::iterator UTI = UT.find(I->second);
385 if (UTI == UT.end())
386 TST.remove(I);
387 else
388 UT.erase(UTI); // Only keep one name for this type.
389 }
390 }
391
392 // UT now contains types that are not named. Loop over it, naming
393 // structure types.
394 //
395 bool Changed = false;
396 unsigned RenameCounter = 0;
397 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
398 I != E; ++I)
Dan Gohman5d995b02008-06-02 21:30:49 +0000399 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
400 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 ++RenameCounter;
402 Changed = true;
403 }
404
405
406 // Loop over all external functions and globals. If we have two with
407 // identical names, merge them.
408 // FIXME: This code should disappear when we don't allow values with the same
409 // names when they have different types!
410 std::map<std::string, GlobalValue*> ExtSymbols;
411 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
412 Function *GV = I++;
413 if (GV->isDeclaration() && GV->hasName()) {
414 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
415 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
416 if (!X.second) {
417 // Found a conflict, replace this global with the previous one.
418 GlobalValue *OldGV = X.first->second;
419 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
420 GV->eraseFromParent();
421 Changed = true;
422 }
423 }
424 }
425 // Do the same for globals.
426 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
427 I != E;) {
428 GlobalVariable *GV = I++;
429 if (GV->isDeclaration() && GV->hasName()) {
430 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
431 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
432 if (!X.second) {
433 // Found a conflict, replace this global with the previous one.
434 GlobalValue *OldGV = X.first->second;
435 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
436 GV->eraseFromParent();
437 Changed = true;
438 }
439 }
440 }
441
442 return Changed;
443}
444
445/// printStructReturnPointerFunctionType - This is like printType for a struct
446/// return type, except, instead of printing the type as void (*)(Struct*, ...)
447/// print it as "Struct (*)(...)", for struct return functions.
David Greene302008d2009-07-14 20:18:05 +0000448void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
Devang Pateld222f862008-09-25 21:00:45 +0000449 const AttrListPtr &PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 const PointerType *TheTy) {
451 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
452 std::stringstream FunctionInnards;
453 FunctionInnards << " (*) (";
454 bool PrintedType = false;
455
456 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
457 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
458 unsigned Idx = 1;
Evan Cheng2054cb02008-01-11 03:07:46 +0000459 for (++I, ++Idx; I != E; ++I, ++Idx) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 if (PrintedType)
461 FunctionInnards << ", ";
Evan Cheng2054cb02008-01-11 03:07:46 +0000462 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000463 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng17254e62008-01-11 09:12:49 +0000464 assert(isa<PointerType>(ArgTy));
465 ArgTy = cast<PointerType>(ArgTy)->getElementType();
466 }
Evan Cheng2054cb02008-01-11 03:07:46 +0000467 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000468 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 PrintedType = true;
470 }
471 if (FTy->isVarArg()) {
472 if (PrintedType)
473 FunctionInnards << ", ...";
474 } else if (!PrintedType) {
475 FunctionInnards << "void";
476 }
477 FunctionInnards << ')';
478 std::string tstr = FunctionInnards.str();
479 printType(Out, RetTy,
Devang Pateld222f862008-09-25 21:00:45 +0000480 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481}
482
Owen Anderson847b99b2008-08-21 00:14:44 +0000483raw_ostream &
David Greene302008d2009-07-14 20:18:05 +0000484CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
485 bool isSigned,
Owen Anderson847b99b2008-08-21 00:14:44 +0000486 const std::string &NameSoFar) {
487 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
488 "Invalid type for printSimpleType");
489 switch (Ty->getTypeID()) {
490 case Type::VoidTyID: return Out << "void " << NameSoFar;
491 case Type::IntegerTyID: {
492 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
493 if (NumBits == 1)
494 return Out << "bool " << NameSoFar;
495 else if (NumBits <= 8)
496 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
497 else if (NumBits <= 16)
498 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
499 else if (NumBits <= 32)
500 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
501 else if (NumBits <= 64)
502 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
503 else {
504 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
505 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
506 }
507 }
508 case Type::FloatTyID: return Out << "float " << NameSoFar;
509 case Type::DoubleTyID: return Out << "double " << NameSoFar;
510 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
511 // present matches host 'long double'.
512 case Type::X86_FP80TyID:
513 case Type::PPC_FP128TyID:
514 case Type::FP128TyID: return Out << "long double " << NameSoFar;
515
516 case Type::VectorTyID: {
517 const VectorType *VTy = cast<VectorType>(Ty);
518 return printSimpleType(Out, VTy->getElementType(), isSigned,
519 " __attribute__((vector_size(" +
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000520 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Owen Anderson847b99b2008-08-21 00:14:44 +0000521 }
522
523 default:
Edwin Török4d9756a2009-07-08 20:53:28 +0000524#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000525 errs() << "Unknown primitive type: " << *Ty << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +0000526#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000527 llvm_unreachable(0);
Owen Anderson847b99b2008-08-21 00:14:44 +0000528 }
529}
530
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531std::ostream &
532CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
Chris Lattnerd8090712008-03-02 03:41:23 +0000533 const std::string &NameSoFar) {
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000534 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 "Invalid type for printSimpleType");
536 switch (Ty->getTypeID()) {
537 case Type::VoidTyID: return Out << "void " << NameSoFar;
538 case Type::IntegerTyID: {
539 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
540 if (NumBits == 1)
541 return Out << "bool " << NameSoFar;
542 else if (NumBits <= 8)
543 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
544 else if (NumBits <= 16)
545 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
546 else if (NumBits <= 32)
547 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
Dan Gohmana2245af2008-04-02 19:40:14 +0000548 else if (NumBits <= 64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
Dan Gohmana2245af2008-04-02 19:40:14 +0000550 else {
551 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
552 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553 }
554 }
555 case Type::FloatTyID: return Out << "float " << NameSoFar;
556 case Type::DoubleTyID: return Out << "double " << NameSoFar;
Dale Johannesen137cef62007-09-17 00:38:27 +0000557 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
558 // present matches host 'long double'.
559 case Type::X86_FP80TyID:
560 case Type::PPC_FP128TyID:
561 case Type::FP128TyID: return Out << "long double " << NameSoFar;
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000562
563 case Type::VectorTyID: {
564 const VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnerd8090712008-03-02 03:41:23 +0000565 return printSimpleType(Out, VTy->getElementType(), isSigned,
Chris Lattnerfddca552008-03-02 03:39:43 +0000566 " __attribute__((vector_size(" +
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000567 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000568 }
569
570 default:
Edwin Török4d9756a2009-07-08 20:53:28 +0000571#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000572 errs() << "Unknown primitive type: " << *Ty << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +0000573#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000574 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 }
576}
577
578// Pass the Type* and the variable name and this prints out the variable
579// declaration.
580//
David Greene302008d2009-07-14 20:18:05 +0000581raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
582 const Type *Ty,
583 bool isSigned, const std::string &NameSoFar,
584 bool IgnoreName, const AttrListPtr &PAL) {
Owen Anderson847b99b2008-08-21 00:14:44 +0000585 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
586 printSimpleType(Out, Ty, isSigned, NameSoFar);
587 return Out;
588 }
589
590 // Check to see if the type is named.
591 if (!IgnoreName || isa<OpaqueType>(Ty)) {
592 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
593 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
594 }
595
596 switch (Ty->getTypeID()) {
597 case Type::FunctionTyID: {
598 const FunctionType *FTy = cast<FunctionType>(Ty);
599 std::stringstream FunctionInnards;
600 FunctionInnards << " (" << NameSoFar << ") (";
601 unsigned Idx = 1;
602 for (FunctionType::param_iterator I = FTy->param_begin(),
603 E = FTy->param_end(); I != E; ++I) {
604 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000605 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Owen Anderson847b99b2008-08-21 00:14:44 +0000606 assert(isa<PointerType>(ArgTy));
607 ArgTy = cast<PointerType>(ArgTy)->getElementType();
608 }
609 if (I != FTy->param_begin())
610 FunctionInnards << ", ";
611 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000612 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Owen Anderson847b99b2008-08-21 00:14:44 +0000613 ++Idx;
614 }
615 if (FTy->isVarArg()) {
616 if (FTy->getNumParams())
617 FunctionInnards << ", ...";
618 } else if (!FTy->getNumParams()) {
619 FunctionInnards << "void";
620 }
621 FunctionInnards << ')';
622 std::string tstr = FunctionInnards.str();
623 printType(Out, FTy->getReturnType(),
Devang Pateld222f862008-09-25 21:00:45 +0000624 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Owen Anderson847b99b2008-08-21 00:14:44 +0000625 return Out;
626 }
627 case Type::StructTyID: {
628 const StructType *STy = cast<StructType>(Ty);
629 Out << NameSoFar + " {\n";
630 unsigned Idx = 0;
631 for (StructType::element_iterator I = STy->element_begin(),
632 E = STy->element_end(); I != E; ++I) {
633 Out << " ";
634 printType(Out, *I, false, "field" + utostr(Idx++));
635 Out << ";\n";
636 }
637 Out << '}';
638 if (STy->isPacked())
639 Out << " __attribute__ ((packed))";
640 return Out;
641 }
642
643 case Type::PointerTyID: {
644 const PointerType *PTy = cast<PointerType>(Ty);
645 std::string ptrName = "*" + NameSoFar;
646
647 if (isa<ArrayType>(PTy->getElementType()) ||
648 isa<VectorType>(PTy->getElementType()))
649 ptrName = "(" + ptrName + ")";
650
651 if (!PAL.isEmpty())
652 // Must be a function ptr cast!
653 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
654 return printType(Out, PTy->getElementType(), false, ptrName);
655 }
656
657 case Type::ArrayTyID: {
658 const ArrayType *ATy = cast<ArrayType>(Ty);
659 unsigned NumElements = ATy->getNumElements();
660 if (NumElements == 0) NumElements = 1;
661 // Arrays are wrapped in structs to allow them to have normal
662 // value semantics (avoiding the array "decay").
663 Out << NameSoFar << " { ";
664 printType(Out, ATy->getElementType(), false,
665 "array[" + utostr(NumElements) + "]");
666 return Out << "; }";
667 }
668
669 case Type::OpaqueTyID: {
Owen Andersonde8a9442009-06-26 19:48:37 +0000670 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Owen Anderson847b99b2008-08-21 00:14:44 +0000671 assert(TypeNames.find(Ty) == TypeNames.end());
672 TypeNames[Ty] = TyName;
673 return Out << TyName << ' ' << NameSoFar;
674 }
675 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000676 llvm_unreachable("Unhandled case in getTypeProps!");
Owen Anderson847b99b2008-08-21 00:14:44 +0000677 }
678
679 return Out;
680}
681
682// Pass the Type* and the variable name and this prints out the variable
683// declaration.
684//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
686 bool isSigned, const std::string &NameSoFar,
Devang Pateld222f862008-09-25 21:00:45 +0000687 bool IgnoreName, const AttrListPtr &PAL) {
Chris Lattnerdb6d5ce2008-03-02 03:33:31 +0000688 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 printSimpleType(Out, Ty, isSigned, NameSoFar);
690 return Out;
691 }
692
693 // Check to see if the type is named.
694 if (!IgnoreName || isa<OpaqueType>(Ty)) {
695 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
696 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
697 }
698
699 switch (Ty->getTypeID()) {
700 case Type::FunctionTyID: {
701 const FunctionType *FTy = cast<FunctionType>(Ty);
702 std::stringstream FunctionInnards;
703 FunctionInnards << " (" << NameSoFar << ") (";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 unsigned Idx = 1;
705 for (FunctionType::param_iterator I = FTy->param_begin(),
706 E = FTy->param_end(); I != E; ++I) {
Evan Chengb8a072c2008-01-12 18:53:07 +0000707 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +0000708 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Chengb8a072c2008-01-12 18:53:07 +0000709 assert(isa<PointerType>(ArgTy));
710 ArgTy = cast<PointerType>(ArgTy)->getElementType();
711 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712 if (I != FTy->param_begin())
713 FunctionInnards << ", ";
Evan Chengb8a072c2008-01-12 18:53:07 +0000714 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +0000715 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 ++Idx;
717 }
718 if (FTy->isVarArg()) {
719 if (FTy->getNumParams())
720 FunctionInnards << ", ...";
721 } else if (!FTy->getNumParams()) {
722 FunctionInnards << "void";
723 }
724 FunctionInnards << ')';
725 std::string tstr = FunctionInnards.str();
726 printType(Out, FTy->getReturnType(),
Devang Pateld222f862008-09-25 21:00:45 +0000727 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728 return Out;
729 }
730 case Type::StructTyID: {
731 const StructType *STy = cast<StructType>(Ty);
732 Out << NameSoFar + " {\n";
733 unsigned Idx = 0;
734 for (StructType::element_iterator I = STy->element_begin(),
735 E = STy->element_end(); I != E; ++I) {
736 Out << " ";
737 printType(Out, *I, false, "field" + utostr(Idx++));
738 Out << ";\n";
739 }
740 Out << '}';
741 if (STy->isPacked())
742 Out << " __attribute__ ((packed))";
743 return Out;
744 }
745
746 case Type::PointerTyID: {
747 const PointerType *PTy = cast<PointerType>(Ty);
748 std::string ptrName = "*" + NameSoFar;
749
750 if (isa<ArrayType>(PTy->getElementType()) ||
751 isa<VectorType>(PTy->getElementType()))
752 ptrName = "(" + ptrName + ")";
753
Chris Lattner1c8733e2008-03-12 17:45:29 +0000754 if (!PAL.isEmpty())
Evan Chengb8a072c2008-01-12 18:53:07 +0000755 // Must be a function ptr cast!
756 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757 return printType(Out, PTy->getElementType(), false, ptrName);
758 }
759
760 case Type::ArrayTyID: {
761 const ArrayType *ATy = cast<ArrayType>(Ty);
762 unsigned NumElements = ATy->getNumElements();
763 if (NumElements == 0) NumElements = 1;
Dan Gohman5d995b02008-06-02 21:30:49 +0000764 // Arrays are wrapped in structs to allow them to have normal
765 // value semantics (avoiding the array "decay").
766 Out << NameSoFar << " { ";
767 printType(Out, ATy->getElementType(), false,
768 "array[" + utostr(NumElements) + "]");
769 return Out << "; }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 }
771
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 case Type::OpaqueTyID: {
Owen Andersonde8a9442009-06-26 19:48:37 +0000773 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774 assert(TypeNames.find(Ty) == TypeNames.end());
775 TypeNames[Ty] = TyName;
776 return Out << TyName << ' ' << NameSoFar;
777 }
778 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000779 llvm_unreachable("Unhandled case in getTypeProps!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 }
781
782 return Out;
783}
784
Dan Gohmanad831302008-07-24 17:57:48 +0000785void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786
787 // As a special case, print the array as a string if it is an array of
788 // ubytes or an array of sbytes with positive values.
789 //
790 const Type *ETy = CPA->getType()->getElementType();
Owen Anderson35b47072009-08-13 21:58:54 +0000791 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
792 ETy == Type::getInt8Ty(CPA->getContext()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793
794 // Make sure the last character is a null char, as automatically added by C
795 if (isString && (CPA->getNumOperands() == 0 ||
796 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
797 isString = false;
798
799 if (isString) {
800 Out << '\"';
801 // Keep track of whether the last number was a hexadecimal escape
802 bool LastWasHex = false;
803
804 // Do not include the last character, which we know is null
805 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
806 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
807
808 // Print it out literally if it is a printable character. The only thing
809 // to be careful about is when the last letter output was a hex escape
810 // code, in which case we have to be careful not to print out hex digits
811 // explicitly (the C compiler thinks it is a continuation of the previous
812 // character, sheesh...)
813 //
814 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
815 LastWasHex = false;
816 if (C == '"' || C == '\\')
Chris Lattner009f3962008-08-21 05:51:43 +0000817 Out << "\\" << (char)C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 else
Chris Lattner009f3962008-08-21 05:51:43 +0000819 Out << (char)C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 } else {
821 LastWasHex = false;
822 switch (C) {
823 case '\n': Out << "\\n"; break;
824 case '\t': Out << "\\t"; break;
825 case '\r': Out << "\\r"; break;
826 case '\v': Out << "\\v"; break;
827 case '\a': Out << "\\a"; break;
828 case '\"': Out << "\\\""; break;
829 case '\'': Out << "\\\'"; break;
830 default:
831 Out << "\\x";
832 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
833 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
834 LastWasHex = true;
835 break;
836 }
837 }
838 }
839 Out << '\"';
840 } else {
841 Out << '{';
842 if (CPA->getNumOperands()) {
843 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +0000844 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
846 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +0000847 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 }
849 }
850 Out << " }";
851 }
852}
853
Dan Gohmanad831302008-07-24 17:57:48 +0000854void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 Out << '{';
856 if (CP->getNumOperands()) {
857 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +0000858 printConstant(cast<Constant>(CP->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
860 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +0000861 printConstant(cast<Constant>(CP->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 }
863 }
864 Out << " }";
865}
866
867// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
868// textually as a double (rather than as a reference to a stack-allocated
869// variable). We decide this by converting CFP to a string and back into a
870// double, and then checking whether the conversion results in a bit-equal
871// double to the original value of CFP. This depends on us and the target C
872// compiler agreeing on the conversion process (which is pretty likely since we
873// only deal in IEEE FP).
874//
875static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Dale Johannesen6e547b42008-10-09 23:00:39 +0000876 bool ignored;
Dale Johannesen137cef62007-09-17 00:38:27 +0000877 // Do long doubles in hex for now.
Owen Anderson35b47072009-08-13 21:58:54 +0000878 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
879 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
Dale Johannesen2fc20782007-09-14 22:26:36 +0000880 return false;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000881 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson35b47072009-08-13 21:58:54 +0000882 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen6e547b42008-10-09 23:00:39 +0000883 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
885 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000886 sprintf(Buffer, "%a", APF.convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 if (!strncmp(Buffer, "0x", 2) ||
888 !strncmp(Buffer, "-0x", 3) ||
889 !strncmp(Buffer, "+0x", 3))
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000890 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 return false;
892#else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000893 std::string StrVal = ftostr(APF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894
895 while (StrVal[0] == ' ')
896 StrVal.erase(StrVal.begin());
897
898 // Check to make sure that the stringized number is not some string like "Inf"
899 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
900 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
901 ((StrVal[0] == '-' || StrVal[0] == '+') &&
902 (StrVal[1] >= '0' && StrVal[1] <= '9')))
903 // Reparse stringized version!
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000904 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 return false;
906#endif
907}
908
909/// Print out the casting for a cast operation. This does the double casting
910/// necessary for conversion to the destination type, if necessary.
911/// @brief Print a cast
912void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
913 // Print the destination type cast
914 switch (opc) {
915 case Instruction::UIToFP:
916 case Instruction::SIToFP:
917 case Instruction::IntToPtr:
918 case Instruction::Trunc:
919 case Instruction::BitCast:
920 case Instruction::FPExt:
921 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
922 Out << '(';
923 printType(Out, DstTy);
924 Out << ')';
925 break;
926 case Instruction::ZExt:
927 case Instruction::PtrToInt:
928 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
929 Out << '(';
930 printSimpleType(Out, DstTy, false);
931 Out << ')';
932 break;
933 case Instruction::SExt:
934 case Instruction::FPToSI: // For these, make sure we get a signed dest
935 Out << '(';
936 printSimpleType(Out, DstTy, true);
937 Out << ')';
938 break;
939 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000940 llvm_unreachable("Invalid cast opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 }
942
943 // Print the source type cast
944 switch (opc) {
945 case Instruction::UIToFP:
946 case Instruction::ZExt:
947 Out << '(';
948 printSimpleType(Out, SrcTy, false);
949 Out << ')';
950 break;
951 case Instruction::SIToFP:
952 case Instruction::SExt:
953 Out << '(';
954 printSimpleType(Out, SrcTy, true);
955 Out << ')';
956 break;
957 case Instruction::IntToPtr:
958 case Instruction::PtrToInt:
959 // Avoid "cast to pointer from integer of different size" warnings
960 Out << "(unsigned long)";
961 break;
962 case Instruction::Trunc:
963 case Instruction::BitCast:
964 case Instruction::FPExt:
965 case Instruction::FPTrunc:
966 case Instruction::FPToSI:
967 case Instruction::FPToUI:
968 break; // These don't need a source cast.
969 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000970 llvm_unreachable("Invalid cast opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 break;
972 }
973}
974
975// printConstant - The LLVM Constant to C Constant converter.
Dan Gohmanad831302008-07-24 17:57:48 +0000976void CWriter::printConstant(Constant *CPV, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
978 switch (CE->getOpcode()) {
979 case Instruction::Trunc:
980 case Instruction::ZExt:
981 case Instruction::SExt:
982 case Instruction::FPTrunc:
983 case Instruction::FPExt:
984 case Instruction::UIToFP:
985 case Instruction::SIToFP:
986 case Instruction::FPToUI:
987 case Instruction::FPToSI:
988 case Instruction::PtrToInt:
989 case Instruction::IntToPtr:
990 case Instruction::BitCast:
991 Out << "(";
992 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
993 if (CE->getOpcode() == Instruction::SExt &&
Owen Anderson35b47072009-08-13 21:58:54 +0000994 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 // Make sure we really sext from bool here by subtracting from 0
996 Out << "0-";
997 }
Dan Gohmanad831302008-07-24 17:57:48 +0000998 printConstant(CE->getOperand(0), Static);
Owen Anderson35b47072009-08-13 21:58:54 +0000999 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 (CE->getOpcode() == Instruction::Trunc ||
1001 CE->getOpcode() == Instruction::FPToUI ||
1002 CE->getOpcode() == Instruction::FPToSI ||
1003 CE->getOpcode() == Instruction::PtrToInt)) {
1004 // Make sure we really truncate to bool here by anding with 1
1005 Out << "&1u";
1006 }
1007 Out << ')';
1008 return;
1009
1010 case Instruction::GetElementPtr:
Chris Lattner8bbc8592008-03-02 08:07:24 +00001011 Out << "(";
1012 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
Dan Gohmanad831302008-07-24 17:57:48 +00001013 gep_type_end(CPV), Static);
Chris Lattner8bbc8592008-03-02 08:07:24 +00001014 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 return;
1016 case Instruction::Select:
1017 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001018 printConstant(CE->getOperand(0), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 Out << '?';
Dan Gohmanad831302008-07-24 17:57:48 +00001020 printConstant(CE->getOperand(1), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 Out << ':';
Dan Gohmanad831302008-07-24 17:57:48 +00001022 printConstant(CE->getOperand(2), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 Out << ')';
1024 return;
1025 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001026 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001028 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001030 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 case Instruction::SDiv:
1032 case Instruction::UDiv:
1033 case Instruction::FDiv:
1034 case Instruction::URem:
1035 case Instruction::SRem:
1036 case Instruction::FRem:
1037 case Instruction::And:
1038 case Instruction::Or:
1039 case Instruction::Xor:
1040 case Instruction::ICmp:
1041 case Instruction::Shl:
1042 case Instruction::LShr:
1043 case Instruction::AShr:
1044 {
1045 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001046 bool NeedsClosingParens = printConstExprCast(CE, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1048 switch (CE->getOpcode()) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00001049 case Instruction::Add:
1050 case Instruction::FAdd: Out << " + "; break;
1051 case Instruction::Sub:
1052 case Instruction::FSub: Out << " - "; break;
1053 case Instruction::Mul:
1054 case Instruction::FMul: Out << " * "; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 case Instruction::URem:
1056 case Instruction::SRem:
1057 case Instruction::FRem: Out << " % "; break;
1058 case Instruction::UDiv:
1059 case Instruction::SDiv:
1060 case Instruction::FDiv: Out << " / "; break;
1061 case Instruction::And: Out << " & "; break;
1062 case Instruction::Or: Out << " | "; break;
1063 case Instruction::Xor: Out << " ^ "; break;
1064 case Instruction::Shl: Out << " << "; break;
1065 case Instruction::LShr:
1066 case Instruction::AShr: Out << " >> "; break;
1067 case Instruction::ICmp:
1068 switch (CE->getPredicate()) {
1069 case ICmpInst::ICMP_EQ: Out << " == "; break;
1070 case ICmpInst::ICMP_NE: Out << " != "; break;
1071 case ICmpInst::ICMP_SLT:
1072 case ICmpInst::ICMP_ULT: Out << " < "; break;
1073 case ICmpInst::ICMP_SLE:
1074 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1075 case ICmpInst::ICMP_SGT:
1076 case ICmpInst::ICMP_UGT: Out << " > "; break;
1077 case ICmpInst::ICMP_SGE:
1078 case ICmpInst::ICMP_UGE: Out << " >= "; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00001079 default: llvm_unreachable("Illegal ICmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 }
1081 break;
Edwin Törökbd448e32009-07-14 16:55:14 +00001082 default: llvm_unreachable("Illegal opcode here!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 }
1084 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1085 if (NeedsClosingParens)
1086 Out << "))";
1087 Out << ')';
1088 return;
1089 }
1090 case Instruction::FCmp: {
1091 Out << '(';
Dan Gohmanad831302008-07-24 17:57:48 +00001092 bool NeedsClosingParens = printConstExprCast(CE, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1094 Out << "0";
1095 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1096 Out << "1";
1097 else {
1098 const char* op = 0;
1099 switch (CE->getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001100 default: llvm_unreachable("Illegal FCmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 case FCmpInst::FCMP_ORD: op = "ord"; break;
1102 case FCmpInst::FCMP_UNO: op = "uno"; break;
1103 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1104 case FCmpInst::FCMP_UNE: op = "une"; break;
1105 case FCmpInst::FCMP_ULT: op = "ult"; break;
1106 case FCmpInst::FCMP_ULE: op = "ule"; break;
1107 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1108 case FCmpInst::FCMP_UGE: op = "uge"; break;
1109 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1110 case FCmpInst::FCMP_ONE: op = "one"; break;
1111 case FCmpInst::FCMP_OLT: op = "olt"; break;
1112 case FCmpInst::FCMP_OLE: op = "ole"; break;
1113 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1114 case FCmpInst::FCMP_OGE: op = "oge"; break;
1115 }
1116 Out << "llvm_fcmp_" << op << "(";
1117 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1118 Out << ", ";
1119 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1120 Out << ")";
1121 }
1122 if (NeedsClosingParens)
1123 Out << "))";
1124 Out << ')';
Anton Korobeynikov44891ce2007-12-21 23:33:44 +00001125 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 }
1127 default:
Edwin Török4d9756a2009-07-08 20:53:28 +00001128#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00001129 errs() << "CWriter Error: Unhandled constant expression: "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 << *CE << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +00001131#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001132 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
Dan Gohman76c2cb42008-05-23 16:57:00 +00001134 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 Out << "((";
1136 printType(Out, CPV->getType()); // sign doesn't matter
Chris Lattnerc72d9e32008-03-02 08:14:45 +00001137 Out << ")/*UNDEF*/";
1138 if (!isa<VectorType>(CPV->getType())) {
1139 Out << "0)";
1140 } else {
1141 Out << "{})";
1142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 return;
1144 }
1145
1146 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1147 const Type* Ty = CI->getType();
Owen Anderson35b47072009-08-13 21:58:54 +00001148 if (Ty == Type::getInt1Ty(CPV->getContext()))
Chris Lattner63fb1f02008-03-02 03:16:38 +00001149 Out << (CI->getZExtValue() ? '1' : '0');
Owen Anderson35b47072009-08-13 21:58:54 +00001150 else if (Ty == Type::getInt32Ty(CPV->getContext()))
Chris Lattner63fb1f02008-03-02 03:16:38 +00001151 Out << CI->getZExtValue() << 'u';
1152 else if (Ty->getPrimitiveSizeInBits() > 32)
1153 Out << CI->getZExtValue() << "ull";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 else {
1155 Out << "((";
1156 printSimpleType(Out, Ty, false) << ')';
1157 if (CI->isMinValue(true))
1158 Out << CI->getZExtValue() << 'u';
1159 else
1160 Out << CI->getSExtValue();
Dale Johannesen8830f922009-05-19 00:46:42 +00001161 Out << ')';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 }
1163 return;
1164 }
1165
1166 switch (CPV->getType()->getTypeID()) {
1167 case Type::FloatTyID:
Dale Johannesen137cef62007-09-17 00:38:27 +00001168 case Type::DoubleTyID:
1169 case Type::X86_FP80TyID:
1170 case Type::PPC_FP128TyID:
1171 case Type::FP128TyID: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 ConstantFP *FPC = cast<ConstantFP>(CPV);
1173 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1174 if (I != FPConstantMap.end()) {
1175 // Because of FP precision problems we must load from a stack allocated
1176 // value that holds the value in hex.
Owen Anderson35b47072009-08-13 21:58:54 +00001177 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1178 "float" :
1179 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1180 "double" :
Dale Johannesen137cef62007-09-17 00:38:27 +00001181 "long double")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 << "*)&FPConstant" << I->second << ')';
1183 } else {
Chris Lattnera68e3512008-10-17 06:11:48 +00001184 double V;
Owen Anderson35b47072009-08-13 21:58:54 +00001185 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
Chris Lattnera68e3512008-10-17 06:11:48 +00001186 V = FPC->getValueAPF().convertToFloat();
Owen Anderson35b47072009-08-13 21:58:54 +00001187 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
Chris Lattnera68e3512008-10-17 06:11:48 +00001188 V = FPC->getValueAPF().convertToDouble();
1189 else {
1190 // Long double. Convert the number to double, discarding precision.
1191 // This is not awesome, but it at least makes the CBE output somewhat
1192 // useful.
1193 APFloat Tmp = FPC->getValueAPF();
1194 bool LosesInfo;
1195 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1196 V = Tmp.convertToDouble();
1197 }
1198
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001199 if (IsNAN(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 // The value is NaN
1201
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001202 // FIXME the actual NaN bits should be emitted.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1204 // it's 0x7ff4.
1205 const unsigned long QuietNaN = 0x7ff8UL;
1206 //const unsigned long SignalNaN = 0x7ff4UL;
1207
1208 // We need to grab the first part of the FP #
1209 char Buffer[100];
1210
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001211 uint64_t ll = DoubleToBits(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1213
1214 std::string Num(&Buffer[0], &Buffer[6]);
1215 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1216
Owen Anderson35b47072009-08-13 21:58:54 +00001217 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1219 << Buffer << "\") /*nan*/ ";
1220 else
1221 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1222 << Buffer << "\") /*nan*/ ";
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001223 } else if (IsInf(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 // The value is Inf
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001225 if (V < 0) Out << '-';
Owen Anderson35b47072009-08-13 21:58:54 +00001226 Out << "LLVM_INF" <<
1227 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 << " /*inf*/ ";
1229 } else {
1230 std::string Num;
1231#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1232 // Print out the constant as a floating point number.
1233 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001234 sprintf(Buffer, "%a", V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 Num = Buffer;
1236#else
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001237 Num = ftostr(FPC->getValueAPF());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238#endif
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001239 Out << Num;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 }
1241 }
1242 break;
1243 }
1244
1245 case Type::ArrayTyID:
Dan Gohman29b19472008-07-23 18:41:03 +00001246 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001247 if (!Static) {
1248 Out << "(";
1249 printType(Out, CPV->getType());
1250 Out << ")";
1251 }
Dan Gohman5d995b02008-06-02 21:30:49 +00001252 Out << "{ "; // Arrays are wrapped in struct types.
Chris Lattner8673e322008-03-02 05:46:57 +00001253 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001254 printConstantArray(CA, Static);
Chris Lattner63fb1f02008-03-02 03:16:38 +00001255 } else {
1256 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1258 Out << '{';
1259 if (AT->getNumElements()) {
1260 Out << ' ';
Owen Andersonaac28372009-07-31 20:28:14 +00001261 Constant *CZ = Constant::getNullValue(AT->getElementType());
Dan Gohmanad831302008-07-24 17:57:48 +00001262 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1264 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001265 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 }
1267 }
1268 Out << " }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 }
Dan Gohman5d995b02008-06-02 21:30:49 +00001270 Out << " }"; // Arrays are wrapped in struct types.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 break;
1272
1273 case Type::VectorTyID:
Chris Lattner70f0f672008-03-02 03:29:50 +00001274 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001275 if (!Static) {
1276 Out << "(";
1277 printType(Out, CPV->getType());
1278 Out << ")";
1279 }
Chris Lattner8673e322008-03-02 05:46:57 +00001280 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001281 printConstantVector(CV, Static);
Chris Lattner63fb1f02008-03-02 03:16:38 +00001282 } else {
1283 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1284 const VectorType *VT = cast<VectorType>(CPV->getType());
1285 Out << "{ ";
Owen Andersonaac28372009-07-31 20:28:14 +00001286 Constant *CZ = Constant::getNullValue(VT->getElementType());
Dan Gohmanad831302008-07-24 17:57:48 +00001287 printConstant(CZ, Static);
Chris Lattner6d4cd9b2008-03-02 03:18:46 +00001288 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
Chris Lattner63fb1f02008-03-02 03:16:38 +00001289 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001290 printConstant(CZ, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 }
1292 Out << " }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 }
1294 break;
1295
1296 case Type::StructTyID:
Dan Gohman29b19472008-07-23 18:41:03 +00001297 // Use C99 compound expression literal initializer syntax.
Dan Gohmanad831302008-07-24 17:57:48 +00001298 if (!Static) {
1299 Out << "(";
1300 printType(Out, CPV->getType());
1301 Out << ")";
1302 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1304 const StructType *ST = cast<StructType>(CPV->getType());
1305 Out << '{';
1306 if (ST->getNumElements()) {
1307 Out << ' ';
Owen Andersonaac28372009-07-31 20:28:14 +00001308 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1310 Out << ", ";
Owen Andersonaac28372009-07-31 20:28:14 +00001311 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 }
1313 }
1314 Out << " }";
1315 } else {
1316 Out << '{';
1317 if (CPV->getNumOperands()) {
1318 Out << ' ';
Dan Gohmanad831302008-07-24 17:57:48 +00001319 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1321 Out << ", ";
Dan Gohmanad831302008-07-24 17:57:48 +00001322 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 }
1324 }
1325 Out << " }";
1326 }
1327 break;
1328
1329 case Type::PointerTyID:
1330 if (isa<ConstantPointerNull>(CPV)) {
1331 Out << "((";
1332 printType(Out, CPV->getType()); // sign doesn't matter
1333 Out << ")/*NULL*/0)";
1334 break;
1335 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
Dan Gohmanad831302008-07-24 17:57:48 +00001336 writeOperand(GV, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 break;
1338 }
1339 // FALL THROUGH
1340 default:
Edwin Török4d9756a2009-07-08 20:53:28 +00001341#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00001342 errs() << "Unknown constant type: " << *CPV << "\n";
Edwin Török4d9756a2009-07-08 20:53:28 +00001343#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001344 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 }
1346}
1347
1348// Some constant expressions need to be casted back to the original types
1349// because their operands were casted to the expected type. This function takes
1350// care of detecting that case and printing the cast for the ConstantExpr.
Dan Gohmanad831302008-07-24 17:57:48 +00001351bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 bool NeedsExplicitCast = false;
1353 const Type *Ty = CE->getOperand(0)->getType();
1354 bool TypeIsSigned = false;
1355 switch (CE->getOpcode()) {
Dan Gohmane1790de2008-07-18 18:43:12 +00001356 case Instruction::Add:
1357 case Instruction::Sub:
1358 case Instruction::Mul:
1359 // We need to cast integer arithmetic so that it is always performed
1360 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 case Instruction::LShr:
1362 case Instruction::URem:
1363 case Instruction::UDiv: NeedsExplicitCast = true; break;
1364 case Instruction::AShr:
1365 case Instruction::SRem:
1366 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1367 case Instruction::SExt:
1368 Ty = CE->getType();
1369 NeedsExplicitCast = true;
1370 TypeIsSigned = true;
1371 break;
1372 case Instruction::ZExt:
1373 case Instruction::Trunc:
1374 case Instruction::FPTrunc:
1375 case Instruction::FPExt:
1376 case Instruction::UIToFP:
1377 case Instruction::SIToFP:
1378 case Instruction::FPToUI:
1379 case Instruction::FPToSI:
1380 case Instruction::PtrToInt:
1381 case Instruction::IntToPtr:
1382 case Instruction::BitCast:
1383 Ty = CE->getType();
1384 NeedsExplicitCast = true;
1385 break;
1386 default: break;
1387 }
1388 if (NeedsExplicitCast) {
1389 Out << "((";
Owen Anderson35b47072009-08-13 21:58:54 +00001390 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 printSimpleType(Out, Ty, TypeIsSigned);
1392 else
1393 printType(Out, Ty); // not integer, sign doesn't matter
1394 Out << ")(";
1395 }
1396 return NeedsExplicitCast;
1397}
1398
1399// Print a constant assuming that it is the operand for a given Opcode. The
1400// opcodes that care about sign need to cast their operands to the expected
1401// type before the operation proceeds. This function does the casting.
1402void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1403
1404 // Extract the operand's type, we'll need it.
1405 const Type* OpTy = CPV->getType();
1406
1407 // Indicate whether to do the cast or not.
1408 bool shouldCast = false;
1409 bool typeIsSigned = false;
1410
1411 // Based on the Opcode for which this Constant is being written, determine
1412 // the new type to which the operand should be casted by setting the value
1413 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1414 // casted below.
1415 switch (Opcode) {
1416 default:
1417 // for most instructions, it doesn't matter
1418 break;
Dan Gohmane1790de2008-07-18 18:43:12 +00001419 case Instruction::Add:
1420 case Instruction::Sub:
1421 case Instruction::Mul:
1422 // We need to cast integer arithmetic so that it is always performed
1423 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 case Instruction::LShr:
1425 case Instruction::UDiv:
1426 case Instruction::URem:
1427 shouldCast = true;
1428 break;
1429 case Instruction::AShr:
1430 case Instruction::SDiv:
1431 case Instruction::SRem:
1432 shouldCast = true;
1433 typeIsSigned = true;
1434 break;
1435 }
1436
1437 // Write out the casted constant if we should, otherwise just write the
1438 // operand.
1439 if (shouldCast) {
1440 Out << "((";
1441 printSimpleType(Out, OpTy, typeIsSigned);
1442 Out << ")";
Dan Gohmanad831302008-07-24 17:57:48 +00001443 printConstant(CPV, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444 Out << ")";
1445 } else
Dan Gohmanad831302008-07-24 17:57:48 +00001446 printConstant(CPV, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447}
1448
1449std::string CWriter::GetValueName(const Value *Operand) {
Chris Lattnerb66867f2009-07-13 23:46:46 +00001450 // Mangle globals with the standard mangler interface for LLC compatibility.
Chris Lattnerd2f59b82010-01-13 19:54:07 +00001451 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1452 SmallString<128> Str;
1453 Mang->getNameWithPrefix(Str, GV, false);
Chris Lattnere295e552010-01-17 19:23:46 +00001454 return Str.str().str();
Chris Lattnerd2f59b82010-01-13 19:54:07 +00001455 }
Chris Lattnerb66867f2009-07-13 23:46:46 +00001456
1457 std::string Name = Operand->getName();
1458
1459 if (Name.empty()) { // Assign unique names to local temporaries.
1460 unsigned &No = AnonValueNumbers[Operand];
1461 if (No == 0)
1462 No = ++NextAnonValueNumber;
1463 Name = "tmp__" + utostr(No);
1464 }
1465
1466 std::string VarName;
1467 VarName.reserve(Name.capacity());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468
Chris Lattnerb66867f2009-07-13 23:46:46 +00001469 for (std::string::iterator I = Name.begin(), E = Name.end();
1470 I != E; ++I) {
1471 char ch = *I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472
Chris Lattnerb66867f2009-07-13 23:46:46 +00001473 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1474 (ch >= '0' && ch <= '9') || ch == '_')) {
1475 char buffer[5];
1476 sprintf(buffer, "_%x_", ch);
1477 VarName += buffer;
1478 } else
1479 VarName += ch;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001480 }
1481
Chris Lattnerb66867f2009-07-13 23:46:46 +00001482 return "llvm_cbe_" + VarName;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483}
1484
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001485/// writeInstComputationInline - Emit the computation for the specified
1486/// instruction inline, with no destination provided.
1487void CWriter::writeInstComputationInline(Instruction &I) {
Dale Johannesen787881e2009-06-18 01:07:23 +00001488 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1489 // Validate this.
1490 const Type *Ty = I.getType();
Owen Anderson35b47072009-08-13 21:58:54 +00001491 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1492 Ty!=Type::getInt8Ty(I.getContext()) &&
1493 Ty!=Type::getInt16Ty(I.getContext()) &&
1494 Ty!=Type::getInt32Ty(I.getContext()) &&
1495 Ty!=Type::getInt64Ty(I.getContext()))) {
Edwin Török4d9756a2009-07-08 20:53:28 +00001496 llvm_report_error("The C backend does not currently support integer "
1497 "types of widths other than 1, 8, 16, 32, 64.\n"
1498 "This is being tracked as PR 4158.");
Dale Johannesen787881e2009-06-18 01:07:23 +00001499 }
1500
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001501 // If this is a non-trivial bool computation, make sure to truncate down to
1502 // a 1 bit value. This is important because we want "add i1 x, y" to return
1503 // "0" when x and y are true, not "2" for example.
1504 bool NeedBoolTrunc = false;
Owen Anderson35b47072009-08-13 21:58:54 +00001505 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1506 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001507 NeedBoolTrunc = true;
1508
1509 if (NeedBoolTrunc)
1510 Out << "((";
1511
1512 visit(I);
1513
1514 if (NeedBoolTrunc)
1515 Out << ")&1)";
1516}
1517
1518
Dan Gohmanad831302008-07-24 17:57:48 +00001519void CWriter::writeOperandInternal(Value *Operand, bool Static) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001521 // Should we inline this instruction to build a tree?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 Out << '(';
Chris Lattnerd70f5a82008-05-31 09:23:55 +00001524 writeInstComputationInline(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 Out << ')';
1526 return;
1527 }
1528
1529 Constant* CPV = dyn_cast<Constant>(Operand);
1530
1531 if (CPV && !isa<GlobalValue>(CPV))
Dan Gohmanad831302008-07-24 17:57:48 +00001532 printConstant(CPV, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 else
1534 Out << GetValueName(Operand);
1535}
1536
Dan Gohmanad831302008-07-24 17:57:48 +00001537void CWriter::writeOperand(Value *Operand, bool Static) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00001538 bool isAddressImplicit = isAddressExposed(Operand);
1539 if (isAddressImplicit)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 Out << "(&"; // Global variables are referenced as their addresses by llvm
1541
Dan Gohmanad831302008-07-24 17:57:48 +00001542 writeOperandInternal(Operand, Static);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543
Chris Lattner8bbc8592008-03-02 08:07:24 +00001544 if (isAddressImplicit)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 Out << ')';
1546}
1547
1548// Some instructions need to have their result value casted back to the
1549// original types because their operands were casted to the expected type.
1550// This function takes care of detecting that case and printing the cast
1551// for the Instruction.
1552bool CWriter::writeInstructionCast(const Instruction &I) {
1553 const Type *Ty = I.getOperand(0)->getType();
1554 switch (I.getOpcode()) {
Dan Gohmane1790de2008-07-18 18:43:12 +00001555 case Instruction::Add:
1556 case Instruction::Sub:
1557 case Instruction::Mul:
1558 // We need to cast integer arithmetic so that it is always performed
1559 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 case Instruction::LShr:
1561 case Instruction::URem:
1562 case Instruction::UDiv:
1563 Out << "((";
1564 printSimpleType(Out, Ty, false);
1565 Out << ")(";
1566 return true;
1567 case Instruction::AShr:
1568 case Instruction::SRem:
1569 case Instruction::SDiv:
1570 Out << "((";
1571 printSimpleType(Out, Ty, true);
1572 Out << ")(";
1573 return true;
1574 default: break;
1575 }
1576 return false;
1577}
1578
1579// Write the operand with a cast to another type based on the Opcode being used.
1580// This will be used in cases where an instruction has specific type
1581// requirements (usually signedness) for its operands.
1582void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1583
1584 // Extract the operand's type, we'll need it.
1585 const Type* OpTy = Operand->getType();
1586
1587 // Indicate whether to do the cast or not.
1588 bool shouldCast = false;
1589
1590 // Indicate whether the cast should be to a signed type or not.
1591 bool castIsSigned = false;
1592
1593 // Based on the Opcode for which this Operand is being written, determine
1594 // the new type to which the operand should be casted by setting the value
1595 // of OpTy. If we change OpTy, also set shouldCast to true.
1596 switch (Opcode) {
1597 default:
1598 // for most instructions, it doesn't matter
1599 break;
Dan Gohmane1790de2008-07-18 18:43:12 +00001600 case Instruction::Add:
1601 case Instruction::Sub:
1602 case Instruction::Mul:
1603 // We need to cast integer arithmetic so that it is always performed
1604 // as unsigned, to avoid undefined behavior on overflow.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605 case Instruction::LShr:
1606 case Instruction::UDiv:
1607 case Instruction::URem: // Cast to unsigned first
1608 shouldCast = true;
1609 castIsSigned = false;
1610 break;
Chris Lattner7ce1ee42007-09-22 20:16:48 +00001611 case Instruction::GetElementPtr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612 case Instruction::AShr:
1613 case Instruction::SDiv:
1614 case Instruction::SRem: // Cast to signed first
1615 shouldCast = true;
1616 castIsSigned = true;
1617 break;
1618 }
1619
1620 // Write out the casted operand if we should, otherwise just write the
1621 // operand.
1622 if (shouldCast) {
1623 Out << "((";
1624 printSimpleType(Out, OpTy, castIsSigned);
1625 Out << ")";
1626 writeOperand(Operand);
1627 Out << ")";
1628 } else
1629 writeOperand(Operand);
1630}
1631
1632// Write the operand with a cast to another type based on the icmp predicate
1633// being used.
Chris Lattner389c9142007-09-15 06:51:03 +00001634void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1635 // This has to do a cast to ensure the operand has the right signedness.
1636 // Also, if the operand is a pointer, we make sure to cast to an integer when
1637 // doing the comparison both for signedness and so that the C compiler doesn't
1638 // optimize things like "p < NULL" to false (p may contain an integer value
1639 // f.e.).
1640 bool shouldCast = Cmp.isRelational();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001641
1642 // Write out the casted operand if we should, otherwise just write the
1643 // operand.
Chris Lattner389c9142007-09-15 06:51:03 +00001644 if (!shouldCast) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 writeOperand(Operand);
Chris Lattner389c9142007-09-15 06:51:03 +00001646 return;
1647 }
1648
1649 // Should this be a signed comparison? If so, convert to signed.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00001650 bool castIsSigned = Cmp.isSigned();
Chris Lattner389c9142007-09-15 06:51:03 +00001651
1652 // If the operand was a pointer, convert to a large integer type.
1653 const Type* OpTy = Operand->getType();
1654 if (isa<PointerType>(OpTy))
Owen Anderson35b47072009-08-13 21:58:54 +00001655 OpTy = TD->getIntPtrType(Operand->getContext());
Chris Lattner389c9142007-09-15 06:51:03 +00001656
1657 Out << "((";
1658 printSimpleType(Out, OpTy, castIsSigned);
1659 Out << ")";
1660 writeOperand(Operand);
1661 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001662}
1663
1664// generateCompilerSpecificCode - This is where we add conditional compilation
1665// directives to cater to specific compilers as need be.
1666//
David Greene302008d2009-07-14 20:18:05 +00001667static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
Dan Gohman3f795232008-04-02 23:52:49 +00001668 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669 // Alloca is hard to get, and we don't want to include stdlib.h here.
1670 Out << "/* get a declaration for alloca */\n"
1671 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1672 << "#define alloca(x) __builtin_alloca((x))\n"
Anton Korobeynikov9664a752009-08-05 09:31:07 +00001673 << "#define _alloca(x) __builtin_alloca((x))\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 << "#elif defined(__APPLE__)\n"
1675 << "extern void *__builtin_alloca(unsigned long);\n"
1676 << "#define alloca(x) __builtin_alloca(x)\n"
1677 << "#define longjmp _longjmp\n"
1678 << "#define setjmp _setjmp\n"
1679 << "#elif defined(__sun__)\n"
1680 << "#if defined(__sparcv9)\n"
1681 << "extern void *__builtin_alloca(unsigned long);\n"
1682 << "#else\n"
1683 << "extern void *__builtin_alloca(unsigned int);\n"
1684 << "#endif\n"
1685 << "#define alloca(x) __builtin_alloca(x)\n"
Anton Korobeynikov9664a752009-08-05 09:31:07 +00001686 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 << "#define alloca(x) __builtin_alloca(x)\n"
1688 << "#elif defined(_MSC_VER)\n"
1689 << "#define inline _inline\n"
1690 << "#define alloca(x) _alloca(x)\n"
1691 << "#else\n"
1692 << "#include <alloca.h>\n"
1693 << "#endif\n\n";
1694
1695 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1696 // If we aren't being compiled with GCC, just drop these attributes.
1697 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1698 << "#define __attribute__(X)\n"
1699 << "#endif\n\n";
1700
1701 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1702 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1703 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1704 << "#elif defined(__GNUC__)\n"
1705 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1706 << "#else\n"
1707 << "#define __EXTERNAL_WEAK__\n"
1708 << "#endif\n\n";
1709
1710 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1711 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1712 << "#define __ATTRIBUTE_WEAK__\n"
1713 << "#elif defined(__GNUC__)\n"
1714 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1715 << "#else\n"
1716 << "#define __ATTRIBUTE_WEAK__\n"
1717 << "#endif\n\n";
1718
1719 // Add hidden visibility support. FIXME: APPLE_CC?
1720 Out << "#if defined(__GNUC__)\n"
1721 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1722 << "#endif\n\n";
1723
1724 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1725 // From the GCC documentation:
1726 //
1727 // double __builtin_nan (const char *str)
1728 //
1729 // This is an implementation of the ISO C99 function nan.
1730 //
1731 // Since ISO C99 defines this function in terms of strtod, which we do
1732 // not implement, a description of the parsing is in order. The string is
1733 // parsed as by strtol; that is, the base is recognized by leading 0 or
1734 // 0x prefixes. The number parsed is placed in the significand such that
1735 // the least significant bit of the number is at the least significant
1736 // bit of the significand. The number is truncated to fit the significand
1737 // field provided. The significand is forced to be a quiet NaN.
1738 //
1739 // This function, if given a string literal, is evaluated early enough
1740 // that it is considered a compile-time constant.
1741 //
1742 // float __builtin_nanf (const char *str)
1743 //
1744 // Similar to __builtin_nan, except the return type is float.
1745 //
1746 // double __builtin_inf (void)
1747 //
1748 // Similar to __builtin_huge_val, except a warning is generated if the
1749 // target floating-point format does not support infinities. This
1750 // function is suitable for implementing the ISO C99 macro INFINITY.
1751 //
1752 // float __builtin_inff (void)
1753 //
1754 // Similar to __builtin_inf, except the return type is float.
1755 Out << "#ifdef __GNUC__\n"
1756 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1757 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1758 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1759 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1760 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1761 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1762 << "#define LLVM_PREFETCH(addr,rw,locality) "
1763 "__builtin_prefetch(addr,rw,locality)\n"
1764 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1765 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1766 << "#define LLVM_ASM __asm__\n"
1767 << "#else\n"
1768 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1769 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1770 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1771 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1772 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1773 << "#define LLVM_INFF 0.0F /* Float */\n"
1774 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1775 << "#define __ATTRIBUTE_CTOR__\n"
1776 << "#define __ATTRIBUTE_DTOR__\n"
1777 << "#define LLVM_ASM(X)\n"
1778 << "#endif\n\n";
1779
1780 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1781 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1782 << "#define __builtin_stack_restore(X) /* noop */\n"
1783 << "#endif\n\n";
1784
Dan Gohman3f795232008-04-02 23:52:49 +00001785 // Output typedefs for 128-bit integers. If these are needed with a
1786 // 32-bit target or with a C compiler that doesn't support mode(TI),
1787 // more drastic measures will be needed.
Chris Lattnerab6d3382008-06-16 04:25:29 +00001788 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1789 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1790 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1791 << "#endif\n\n";
Dan Gohmana2245af2008-04-02 19:40:14 +00001792
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 // Output target-specific code that should be inserted into main.
1794 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001795}
1796
1797/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1798/// the StaticTors set.
1799static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1800 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1801 if (!InitList) return;
1802
1803 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1804 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1805 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1806
1807 if (CS->getOperand(1)->isNullValue())
1808 return; // Found a null terminator, exit printing.
1809 Constant *FP = CS->getOperand(1);
1810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1811 if (CE->isCast())
1812 FP = CE->getOperand(0);
1813 if (Function *F = dyn_cast<Function>(FP))
1814 StaticTors.insert(F);
1815 }
1816}
1817
1818enum SpecialGlobalClass {
1819 NotSpecial = 0,
1820 GlobalCtors, GlobalDtors,
1821 NotPrinted
1822};
1823
1824/// getGlobalVariableClass - If this is a global that is specially recognized
1825/// by LLVM, return a code that indicates how we should handle it.
1826static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1827 // If this is a global ctors/dtors list, handle it now.
1828 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1829 if (GV->getName() == "llvm.global_ctors")
1830 return GlobalCtors;
1831 else if (GV->getName() == "llvm.global_dtors")
1832 return GlobalDtors;
1833 }
1834
1835 // Otherwise, it it is other metadata, don't print it. This catches things
1836 // like debug information.
1837 if (GV->getSection() == "llvm.metadata")
1838 return NotPrinted;
1839
1840 return NotSpecial;
1841}
1842
Anton Korobeynikov865e6752009-08-05 09:29:56 +00001843// PrintEscapedString - Print each character of the specified string, escaping
1844// it if it is not printable or if it is an escape char.
1845static void PrintEscapedString(const char *Str, unsigned Length,
1846 raw_ostream &Out) {
1847 for (unsigned i = 0; i != Length; ++i) {
1848 unsigned char C = Str[i];
1849 if (isprint(C) && C != '\\' && C != '"')
1850 Out << C;
1851 else if (C == '\\')
1852 Out << "\\\\";
1853 else if (C == '\"')
1854 Out << "\\\"";
1855 else if (C == '\t')
1856 Out << "\\t";
1857 else
1858 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1859 }
1860}
1861
1862// PrintEscapedString - Print each character of the specified string, escaping
1863// it if it is not printable or if it is an escape char.
1864static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1865 PrintEscapedString(Str.c_str(), Str.size(), Out);
1866}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867
1868bool CWriter::doInitialization(Module &M) {
Daniel Dunbar5392e062009-07-17 03:43:21 +00001869 FunctionPass::doInitialization(M);
1870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871 // Initialize
1872 TheModule = &M;
1873
1874 TD = new TargetData(&M);
1875 IL = new IntrinsicLowering(*TD);
1876 IL->AddPrototypes(M);
1877
Chris Lattner63ab9bb2010-01-17 18:22:35 +00001878#if 0
1879 std::string Triple = TheModule->getTargetTriple();
1880 if (Triple.empty())
1881 Triple = llvm::sys::getHostTriple();
1882
1883 std::string E;
1884 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1885 TAsm = Match->createAsmInfo(Triple);
1886#endif
1887 TAsm = new CBEMCAsmInfo();
1888 Mang = new Mangler(*TAsm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001889
1890 // Keep track of which functions are static ctors/dtors so they can have
1891 // an attribute added to their prototypes.
1892 std::set<Function*> StaticCtors, StaticDtors;
1893 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1894 I != E; ++I) {
1895 switch (getGlobalVariableClass(I)) {
1896 default: break;
1897 case GlobalCtors:
1898 FindStaticTors(I, StaticCtors);
1899 break;
1900 case GlobalDtors:
1901 FindStaticTors(I, StaticDtors);
1902 break;
1903 }
1904 }
1905
1906 // get declaration for alloca
1907 Out << "/* Provide Declarations */\n";
1908 Out << "#include <stdarg.h>\n"; // Varargs support
1909 Out << "#include <setjmp.h>\n"; // Unwind support
Dan Gohman3f795232008-04-02 23:52:49 +00001910 generateCompilerSpecificCode(Out, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911
1912 // Provide a definition for `bool' if not compiling with a C++ compiler.
1913 Out << "\n"
1914 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1915
1916 << "\n\n/* Support for floating point constants */\n"
1917 << "typedef unsigned long long ConstantDoubleTy;\n"
1918 << "typedef unsigned int ConstantFloatTy;\n"
Dale Johannesen137cef62007-09-17 00:38:27 +00001919 << "typedef struct { unsigned long long f1; unsigned short f2; "
1920 "unsigned short pad[3]; } ConstantFP80Ty;\n"
Dale Johannesen091dcfd2007-10-15 01:05:37 +00001921 // This is used for both kinds of 128-bit long double; meaning differs.
Dale Johannesen137cef62007-09-17 00:38:27 +00001922 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1923 " ConstantFP128Ty;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924 << "\n\n/* Global Declarations */\n";
1925
1926 // First output all the declarations for the program, because C requires
1927 // Functions & globals to be declared before they are used.
1928 //
Anton Korobeynikov865e6752009-08-05 09:29:56 +00001929 if (!M.getModuleInlineAsm().empty()) {
1930 Out << "/* Module asm statements */\n"
1931 << "asm(";
1932
1933 // Split the string into lines, to make it easier to read the .ll file.
1934 std::string Asm = M.getModuleInlineAsm();
1935 size_t CurPos = 0;
1936 size_t NewLine = Asm.find_first_of('\n', CurPos);
1937 while (NewLine != std::string::npos) {
1938 // We found a newline, print the portion of the asm string from the
1939 // last newline up to this newline.
1940 Out << "\"";
1941 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1942 Out);
1943 Out << "\\n\"\n";
1944 CurPos = NewLine+1;
1945 NewLine = Asm.find_first_of('\n', CurPos);
1946 }
1947 Out << "\"";
1948 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1949 Out << "\");\n"
1950 << "/* End Module asm statements */\n";
1951 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952
1953 // Loop over the symbol table, emitting all named constants...
1954 printModuleTypes(M.getTypeSymbolTable());
1955
1956 // Global variable declarations...
1957 if (!M.global_empty()) {
1958 Out << "\n/* External Global Variable Declarations */\n";
1959 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1960 I != E; ++I) {
1961
Dale Johannesen49c44122008-05-14 20:12:51 +00001962 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1963 I->hasCommonLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001964 Out << "extern ";
1965 else if (I->hasDLLImportLinkage())
1966 Out << "__declspec(dllimport) ";
1967 else
1968 continue; // Internal Global
1969
1970 // Thread Local Storage
1971 if (I->isThreadLocal())
1972 Out << "__thread ";
1973
1974 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1975
1976 if (I->hasExternalWeakLinkage())
1977 Out << " __EXTERNAL_WEAK__";
1978 Out << ";\n";
1979 }
1980 }
1981
1982 // Function declarations
1983 Out << "\n/* Function Declarations */\n";
1984 Out << "double fmod(double, double);\n"; // Support for FP rem
1985 Out << "float fmodf(float, float);\n";
Dale Johannesen137cef62007-09-17 00:38:27 +00001986 Out << "long double fmodl(long double, long double);\n";
Evan Chengd2d22fe2008-06-07 07:50:29 +00001987
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1989 // Don't print declarations for intrinsic functions.
Duncan Sands79d28872007-12-03 20:06:50 +00001990 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001991 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1992 if (I->hasExternalWeakLinkage())
1993 Out << "extern ";
1994 printFunctionSignature(I, true);
Evan Chengd2d22fe2008-06-07 07:50:29 +00001995 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 Out << " __ATTRIBUTE_WEAK__";
1997 if (I->hasExternalWeakLinkage())
1998 Out << " __EXTERNAL_WEAK__";
1999 if (StaticCtors.count(I))
2000 Out << " __ATTRIBUTE_CTOR__";
2001 if (StaticDtors.count(I))
2002 Out << " __ATTRIBUTE_DTOR__";
2003 if (I->hasHiddenVisibility())
2004 Out << " __HIDDEN__";
Evan Chengd2d22fe2008-06-07 07:50:29 +00002005
2006 if (I->hasName() && I->getName()[0] == 1)
Daniel Dunbar936763a2009-07-22 21:10:12 +00002007 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
Evan Chengd2d22fe2008-06-07 07:50:29 +00002008
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002009 Out << ";\n";
2010 }
2011 }
2012
2013 // Output the global variable declarations
2014 if (!M.global_empty()) {
2015 Out << "\n\n/* Global Variable Declarations */\n";
2016 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2017 I != E; ++I)
2018 if (!I->isDeclaration()) {
2019 // Ignore special globals, such as debug info.
2020 if (getGlobalVariableClass(I))
2021 continue;
2022
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002023 if (I->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002024 Out << "static ";
2025 else
2026 Out << "extern ";
2027
2028 // Thread Local Storage
2029 if (I->isThreadLocal())
2030 Out << "__thread ";
2031
2032 printType(Out, I->getType()->getElementType(), false,
2033 GetValueName(I));
2034
2035 if (I->hasLinkOnceLinkage())
2036 Out << " __attribute__((common))";
Dale Johannesen49c44122008-05-14 20:12:51 +00002037 else if (I->hasCommonLinkage()) // FIXME is this right?
2038 Out << " __ATTRIBUTE_WEAK__";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039 else if (I->hasWeakLinkage())
2040 Out << " __ATTRIBUTE_WEAK__";
2041 else if (I->hasExternalWeakLinkage())
2042 Out << " __EXTERNAL_WEAK__";
2043 if (I->hasHiddenVisibility())
2044 Out << " __HIDDEN__";
2045 Out << ";\n";
2046 }
2047 }
2048
2049 // Output the global variable definitions and contents...
2050 if (!M.global_empty()) {
2051 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Evan Chengd2d22fe2008-06-07 07:50:29 +00002052 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 I != E; ++I)
2054 if (!I->isDeclaration()) {
2055 // Ignore special globals, such as debug info.
2056 if (getGlobalVariableClass(I))
2057 continue;
2058
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002059 if (I->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 Out << "static ";
2061 else if (I->hasDLLImportLinkage())
2062 Out << "__declspec(dllimport) ";
2063 else if (I->hasDLLExportLinkage())
2064 Out << "__declspec(dllexport) ";
2065
2066 // Thread Local Storage
2067 if (I->isThreadLocal())
2068 Out << "__thread ";
2069
2070 printType(Out, I->getType()->getElementType(), false,
2071 GetValueName(I));
2072 if (I->hasLinkOnceLinkage())
2073 Out << " __attribute__((common))";
2074 else if (I->hasWeakLinkage())
2075 Out << " __ATTRIBUTE_WEAK__";
Dale Johannesen49c44122008-05-14 20:12:51 +00002076 else if (I->hasCommonLinkage())
2077 Out << " __ATTRIBUTE_WEAK__";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078
2079 if (I->hasHiddenVisibility())
2080 Out << " __HIDDEN__";
2081
2082 // If the initializer is not null, emit the initializer. If it is null,
2083 // we try to avoid emitting large amounts of zeros. The problem with
2084 // this, however, occurs when the variable has weak linkage. In this
2085 // case, the assembler will complain about the variable being both weak
2086 // and common, so we disable this optimization.
Dale Johannesen49c44122008-05-14 20:12:51 +00002087 // FIXME common linkage should avoid this problem.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088 if (!I->getInitializer()->isNullValue()) {
2089 Out << " = " ;
Dan Gohmanad831302008-07-24 17:57:48 +00002090 writeOperand(I->getInitializer(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002091 } else if (I->hasWeakLinkage()) {
2092 // We have to specify an initializer, but it doesn't have to be
2093 // complete. If the value is an aggregate, print out { 0 }, and let
2094 // the compiler figure out the rest of the zeros.
2095 Out << " = " ;
2096 if (isa<StructType>(I->getInitializer()->getType()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002097 isa<VectorType>(I->getInitializer()->getType())) {
2098 Out << "{ 0 }";
Dan Gohman5d995b02008-06-02 21:30:49 +00002099 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2100 // As with structs and vectors, but with an extra set of braces
2101 // because arrays are wrapped in structs.
2102 Out << "{ { 0 } }";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103 } else {
2104 // Just print it out normally.
Dan Gohmanad831302008-07-24 17:57:48 +00002105 writeOperand(I->getInitializer(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106 }
2107 }
2108 Out << ";\n";
2109 }
2110 }
2111
2112 if (!M.empty())
2113 Out << "\n\n/* Function Bodies */\n";
2114
2115 // Emit some helper functions for dealing with FCMP instruction's
2116 // predicates
2117 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2118 Out << "return X == X && Y == Y; }\n";
2119 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2120 Out << "return X != X || Y != Y; }\n";
2121 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2122 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2123 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2124 Out << "return X != Y; }\n";
2125 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2126 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2127 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2128 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2129 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2130 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2131 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2132 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2133 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2134 Out << "return X == Y ; }\n";
2135 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2136 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2137 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2138 Out << "return X < Y ; }\n";
2139 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2140 Out << "return X > Y ; }\n";
2141 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2142 Out << "return X <= Y ; }\n";
2143 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2144 Out << "return X >= Y ; }\n";
2145 return false;
2146}
2147
2148
2149/// Output all floating point constants that cannot be printed accurately...
2150void CWriter::printFloatingPointConstants(Function &F) {
2151 // Scan the module for floating point constants. If any FP constant is used
2152 // in the function, we want to redirect it here so that we do not depend on
2153 // the precision of the printed form, unless the printed form preserves
2154 // precision.
2155 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002156 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2157 I != E; ++I)
Chris Lattnerf6e12012008-10-22 04:53:16 +00002158 printFloatingPointConstants(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159
2160 Out << '\n';
2161}
2162
Chris Lattnerf6e12012008-10-22 04:53:16 +00002163void CWriter::printFloatingPointConstants(const Constant *C) {
2164 // If this is a constant expression, recursively check for constant fp values.
2165 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2166 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2167 printFloatingPointConstants(CE->getOperand(i));
2168 return;
2169 }
2170
2171 // Otherwise, check for a FP constant that we need to print.
2172 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2173 if (FPC == 0 ||
2174 // Do not put in FPConstantMap if safe.
2175 isFPCSafeToPrint(FPC) ||
2176 // Already printed this constant?
2177 FPConstantMap.count(FPC))
2178 return;
2179
2180 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2181
Owen Anderson35b47072009-08-13 21:58:54 +00002182 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002183 double Val = FPC->getValueAPF().convertToDouble();
2184 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2185 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2186 << " = 0x" << utohexstr(i)
2187 << "ULL; /* " << Val << " */\n";
Owen Anderson35b47072009-08-13 21:58:54 +00002188 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002189 float Val = FPC->getValueAPF().convertToFloat();
2190 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2191 getZExtValue();
2192 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2193 << " = 0x" << utohexstr(i)
2194 << "U; /* " << Val << " */\n";
Owen Anderson35b47072009-08-13 21:58:54 +00002195 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002196 // api needed to prevent premature destruction
2197 APInt api = FPC->getValueAPF().bitcastToAPInt();
2198 const uint64_t *p = api.getRawData();
2199 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
Dale Johannesen0a92eac2009-03-23 21:16:53 +00002200 << " = { 0x" << utohexstr(p[0])
2201 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
Chris Lattnerf6e12012008-10-22 04:53:16 +00002202 << "}; /* Long double constant */\n";
Anton Korobeynikov3e721692009-08-26 17:39:23 +00002203 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2204 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
Chris Lattnerf6e12012008-10-22 04:53:16 +00002205 APInt api = FPC->getValueAPF().bitcastToAPInt();
2206 const uint64_t *p = api.getRawData();
2207 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2208 << " = { 0x"
2209 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2210 << "}; /* Long double constant */\n";
2211
2212 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002213 llvm_unreachable("Unknown float type!");
Chris Lattnerf6e12012008-10-22 04:53:16 +00002214 }
2215}
2216
2217
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218
2219/// printSymbolTable - Run through symbol table looking for type names. If a
2220/// type name is found, emit its declaration...
2221///
2222void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2223 Out << "/* Helper union for bitcasts */\n";
2224 Out << "typedef union {\n";
2225 Out << " unsigned int Int32;\n";
2226 Out << " unsigned long long Int64;\n";
2227 Out << " float Float;\n";
2228 Out << " double Double;\n";
2229 Out << "} llvmBitCastUnion;\n";
2230
2231 // We are only interested in the type plane of the symbol table.
2232 TypeSymbolTable::const_iterator I = TST.begin();
2233 TypeSymbolTable::const_iterator End = TST.end();
2234
2235 // If there are no type names, exit early.
2236 if (I == End) return;
2237
2238 // Print out forward declarations for structure types before anything else!
2239 Out << "/* Structure forward decls */\n";
2240 for (; I != End; ++I) {
Chris Lattnerd2f59b82010-01-13 19:54:07 +00002241 std::string Name = "struct " + Mangle("l_"+I->first);
2242 Out << Name << ";\n";
2243 TypeNames.insert(std::make_pair(I->second, Name));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244 }
2245
2246 Out << '\n';
2247
2248 // Now we can print out typedefs. Above, we guaranteed that this can only be
2249 // for struct or opaque types.
2250 Out << "/* Typedefs */\n";
2251 for (I = TST.begin(); I != End; ++I) {
Chris Lattnerd2f59b82010-01-13 19:54:07 +00002252 std::string Name = Mangle("l_"+I->first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 Out << "typedef ";
Chris Lattnerd2f59b82010-01-13 19:54:07 +00002254 printType(Out, I->second, false, Name);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255 Out << ";\n";
2256 }
2257
2258 Out << '\n';
2259
2260 // Keep track of which structures have been printed so far...
Dan Gohman5d995b02008-06-02 21:30:49 +00002261 std::set<const Type *> StructPrinted;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262
2263 // Loop over all structures then push them into the stack so they are
2264 // printed in the correct order.
2265 //
2266 Out << "/* Structure contents */\n";
2267 for (I = TST.begin(); I != End; ++I)
Dan Gohman5d995b02008-06-02 21:30:49 +00002268 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 // Only print out used types!
Dan Gohman5d995b02008-06-02 21:30:49 +00002270 printContainedStructs(I->second, StructPrinted);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271}
2272
2273// Push the struct onto the stack and recursively push all structs
2274// this one depends on.
2275//
2276// TODO: Make this work properly with vector types
2277//
2278void CWriter::printContainedStructs(const Type *Ty,
Dan Gohman5d995b02008-06-02 21:30:49 +00002279 std::set<const Type*> &StructPrinted) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280 // Don't walk through pointers.
2281 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2282
2283 // Print all contained types first.
2284 for (Type::subtype_iterator I = Ty->subtype_begin(),
2285 E = Ty->subtype_end(); I != E; ++I)
2286 printContainedStructs(*I, StructPrinted);
2287
Dan Gohman5d995b02008-06-02 21:30:49 +00002288 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002289 // Check to see if we have already printed this struct.
Dan Gohman5d995b02008-06-02 21:30:49 +00002290 if (StructPrinted.insert(Ty).second) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 // Print structure type out.
Dan Gohman5d995b02008-06-02 21:30:49 +00002292 std::string Name = TypeNames[Ty];
2293 printType(Out, Ty, false, Name, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294 Out << ";\n\n";
2295 }
2296 }
2297}
2298
2299void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2300 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel949a4b72008-03-03 21:46:28 +00002301 bool isStructReturn = F->hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002303 if (F->hasLocalLinkage()) Out << "static ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002304 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2305 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2306 switch (F->getCallingConv()) {
2307 case CallingConv::X86_StdCall:
Nick Lewyckyc0b01ea2008-11-26 03:17:27 +00002308 Out << "__attribute__((stdcall)) ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309 break;
2310 case CallingConv::X86_FastCall:
Nick Lewyckyc0b01ea2008-11-26 03:17:27 +00002311 Out << "__attribute__((fastcall)) ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312 break;
Sandeep Patel5838baa2009-09-02 08:44:58 +00002313 default:
2314 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315 }
2316
2317 // Loop over the arguments, printing them...
2318 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Devang Pateld222f862008-09-25 21:00:45 +00002319 const AttrListPtr &PAL = F->getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320
2321 std::stringstream FunctionInnards;
2322
2323 // Print out the name...
2324 FunctionInnards << GetValueName(F) << '(';
2325
2326 bool PrintedArg = false;
2327 if (!F->isDeclaration()) {
2328 if (!F->arg_empty()) {
2329 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
Evan Cheng2054cb02008-01-11 03:07:46 +00002330 unsigned Idx = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002331
2332 // If this is a struct-return function, don't print the hidden
2333 // struct-return argument.
2334 if (isStructReturn) {
2335 assert(I != E && "Invalid struct return function!");
2336 ++I;
Evan Cheng2054cb02008-01-11 03:07:46 +00002337 ++Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 }
2339
2340 std::string ArgName;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341 for (; I != E; ++I) {
2342 if (PrintedArg) FunctionInnards << ", ";
2343 if (I->hasName() || !Prototype)
2344 ArgName = GetValueName(I);
2345 else
2346 ArgName = "";
Evan Cheng2054cb02008-01-11 03:07:46 +00002347 const Type *ArgTy = I->getType();
Devang Pateld222f862008-09-25 21:00:45 +00002348 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Cheng17254e62008-01-11 09:12:49 +00002349 ArgTy = cast<PointerType>(ArgTy)->getElementType();
Chris Lattner8bbc8592008-03-02 08:07:24 +00002350 ByValParams.insert(I);
Evan Cheng17254e62008-01-11 09:12:49 +00002351 }
Evan Cheng2054cb02008-01-11 03:07:46 +00002352 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +00002353 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002354 ArgName);
2355 PrintedArg = true;
2356 ++Idx;
2357 }
2358 }
2359 } else {
2360 // Loop over the arguments, printing them.
2361 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
Evan Chengf8956382008-01-11 23:10:11 +00002362 unsigned Idx = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002363
2364 // If this is a struct-return function, don't print the hidden
2365 // struct-return argument.
2366 if (isStructReturn) {
2367 assert(I != E && "Invalid struct return function!");
2368 ++I;
Evan Chengf8956382008-01-11 23:10:11 +00002369 ++Idx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002370 }
2371
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002372 for (; I != E; ++I) {
2373 if (PrintedArg) FunctionInnards << ", ";
Evan Chengf8956382008-01-11 23:10:11 +00002374 const Type *ArgTy = *I;
Devang Pateld222f862008-09-25 21:00:45 +00002375 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
Evan Chengf8956382008-01-11 23:10:11 +00002376 assert(isa<PointerType>(ArgTy));
2377 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2378 }
2379 printType(FunctionInnards, ArgTy,
Devang Pateld222f862008-09-25 21:00:45 +00002380 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002381 PrintedArg = true;
2382 ++Idx;
2383 }
2384 }
2385
2386 // Finish printing arguments... if this is a vararg function, print the ...,
2387 // unless there are no known types, in which case, we just emit ().
2388 //
2389 if (FT->isVarArg() && PrintedArg) {
2390 if (PrintedArg) FunctionInnards << ", ";
2391 FunctionInnards << "..."; // Output varargs portion of signature!
2392 } else if (!FT->isVarArg() && !PrintedArg) {
2393 FunctionInnards << "void"; // ret() -> ret(void) in C.
2394 }
2395 FunctionInnards << ')';
2396
2397 // Get the return tpe for the function.
2398 const Type *RetTy;
2399 if (!isStructReturn)
2400 RetTy = F->getReturnType();
2401 else {
2402 // If this is a struct-return function, print the struct-return type.
2403 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2404 }
2405
2406 // Print out the return type and the signature built above.
2407 printType(Out, RetTy,
Devang Pateld222f862008-09-25 21:00:45 +00002408 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002409 FunctionInnards.str());
2410}
2411
2412static inline bool isFPIntBitCast(const Instruction &I) {
2413 if (!isa<BitCastInst>(I))
2414 return false;
2415 const Type *SrcTy = I.getOperand(0)->getType();
2416 const Type *DstTy = I.getType();
2417 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2418 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2419}
2420
2421void CWriter::printFunction(Function &F) {
2422 /// isStructReturn - Should this function actually return a struct by-value?
Devang Patel949a4b72008-03-03 21:46:28 +00002423 bool isStructReturn = F.hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002424
2425 printFunctionSignature(&F, false);
2426 Out << " {\n";
2427
2428 // If this is a struct return function, handle the result with magic.
2429 if (isStructReturn) {
2430 const Type *StructTy =
2431 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2432 Out << " ";
2433 printType(Out, StructTy, false, "StructReturn");
2434 Out << "; /* Struct return temporary */\n";
2435
2436 Out << " ";
2437 printType(Out, F.arg_begin()->getType(), false,
2438 GetValueName(F.arg_begin()));
2439 Out << " = &StructReturn;\n";
2440 }
2441
2442 bool PrintedVar = false;
2443
2444 // print local variable information for the function
2445 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2446 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2447 Out << " ";
2448 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2449 Out << "; /* Address-exposed local */\n";
2450 PrintedVar = true;
Owen Anderson35b47072009-08-13 21:58:54 +00002451 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2452 !isInlinableInst(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002453 Out << " ";
2454 printType(Out, I->getType(), false, GetValueName(&*I));
2455 Out << ";\n";
2456
2457 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2458 Out << " ";
2459 printType(Out, I->getType(), false,
2460 GetValueName(&*I)+"__PHI_TEMPORARY");
2461 Out << ";\n";
2462 }
2463 PrintedVar = true;
2464 }
2465 // We need a temporary for the BitCast to use so it can pluck a value out
2466 // of a union to do the BitCast. This is separate from the need for a
2467 // variable to hold the result of the BitCast.
2468 if (isFPIntBitCast(*I)) {
2469 Out << " llvmBitCastUnion " << GetValueName(&*I)
2470 << "__BITCAST_TEMPORARY;\n";
2471 PrintedVar = true;
2472 }
2473 }
2474
2475 if (PrintedVar)
2476 Out << '\n';
2477
2478 if (F.hasExternalLinkage() && F.getName() == "main")
2479 Out << " CODE_FOR_MAIN();\n";
2480
2481 // print the basic blocks
2482 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2483 if (Loop *L = LI->getLoopFor(BB)) {
2484 if (L->getHeader() == BB && L->getParentLoop() == 0)
2485 printLoop(L);
2486 } else {
2487 printBasicBlock(BB);
2488 }
2489 }
2490
2491 Out << "}\n\n";
2492}
2493
2494void CWriter::printLoop(Loop *L) {
2495 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2496 << "' to make GCC happy */\n";
2497 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2498 BasicBlock *BB = L->getBlocks()[i];
2499 Loop *BBLoop = LI->getLoopFor(BB);
2500 if (BBLoop == L)
2501 printBasicBlock(BB);
2502 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2503 printLoop(BBLoop);
2504 }
2505 Out << " } while (1); /* end of syntactic loop '"
2506 << L->getHeader()->getName() << "' */\n";
2507}
2508
2509void CWriter::printBasicBlock(BasicBlock *BB) {
2510
2511 // Don't print the label for the basic block if there are no uses, or if
2512 // the only terminator use is the predecessor basic block's terminator.
2513 // We have to scan the use list because PHI nodes use basic blocks too but
2514 // do not require a label to be generated.
2515 //
2516 bool NeedsLabel = false;
2517 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2518 if (isGotoCodeNecessary(*PI, BB)) {
2519 NeedsLabel = true;
2520 break;
2521 }
2522
2523 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2524
2525 // Output all of the instructions in the basic block...
2526 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2527 ++II) {
2528 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Owen Anderson35b47072009-08-13 21:58:54 +00002529 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2530 !isInlineAsm(*II))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531 outputLValue(II);
2532 else
2533 Out << " ";
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002534 writeInstComputationInline(*II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535 Out << ";\n";
2536 }
2537 }
2538
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002539 // Don't emit prefix or suffix for the terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002540 visit(*BB->getTerminator());
2541}
2542
2543
2544// Specific Instruction type classes... note that all of the casts are
2545// necessary because we use the instruction classes as opaque types...
2546//
2547void CWriter::visitReturnInst(ReturnInst &I) {
2548 // If this is a struct return function, return the temporary struct.
Devang Patel949a4b72008-03-03 21:46:28 +00002549 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550
2551 if (isStructReturn) {
2552 Out << " return StructReturn;\n";
2553 return;
2554 }
2555
2556 // Don't output a void return if this is the last basic block in the function
2557 if (I.getNumOperands() == 0 &&
2558 &*--I.getParent()->getParent()->end() == I.getParent() &&
2559 !I.getParent()->size() == 1) {
2560 return;
2561 }
2562
Dan Gohman93d04582008-04-23 21:49:29 +00002563 if (I.getNumOperands() > 1) {
2564 Out << " {\n";
2565 Out << " ";
2566 printType(Out, I.getParent()->getParent()->getReturnType());
2567 Out << " llvm_cbe_mrv_temp = {\n";
2568 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2569 Out << " ";
2570 writeOperand(I.getOperand(i));
2571 if (i != e - 1)
2572 Out << ",";
2573 Out << "\n";
2574 }
2575 Out << " };\n";
2576 Out << " return llvm_cbe_mrv_temp;\n";
2577 Out << " }\n";
2578 return;
2579 }
2580
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002581 Out << " return";
2582 if (I.getNumOperands()) {
2583 Out << ' ';
2584 writeOperand(I.getOperand(0));
2585 }
2586 Out << ";\n";
2587}
2588
2589void CWriter::visitSwitchInst(SwitchInst &SI) {
2590
2591 Out << " switch (";
2592 writeOperand(SI.getOperand(0));
2593 Out << ") {\n default:\n";
2594 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2595 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2596 Out << ";\n";
2597 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2598 Out << " case ";
2599 writeOperand(SI.getOperand(i));
2600 Out << ":\n";
2601 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2602 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2603 printBranchToBlock(SI.getParent(), Succ, 2);
Chris Lattnerb44b4292009-12-03 00:50:42 +00002604 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002605 Out << " break;\n";
2606 }
2607 Out << " }\n";
2608}
2609
Chris Lattner4c3800f2009-10-28 00:19:10 +00002610void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
Chris Lattner20e88f52009-10-27 21:21:06 +00002611 Out << " goto *(void*)(";
2612 writeOperand(IBI.getOperand(0));
2613 Out << ");\n";
2614}
2615
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002616void CWriter::visitUnreachableInst(UnreachableInst &I) {
2617 Out << " /*UNREACHABLE*/;\n";
2618}
2619
2620bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2621 /// FIXME: This should be reenabled, but loop reordering safe!!
2622 return true;
2623
Chris Lattnerb44b4292009-12-03 00:50:42 +00002624 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002625 return true; // Not the direct successor, we need a goto.
2626
2627 //isa<SwitchInst>(From->getTerminator())
2628
2629 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2630 return true;
2631 return false;
2632}
2633
2634void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2635 BasicBlock *Successor,
2636 unsigned Indent) {
2637 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2638 PHINode *PN = cast<PHINode>(I);
2639 // Now we have to do the printing.
2640 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2641 if (!isa<UndefValue>(IV)) {
2642 Out << std::string(Indent, ' ');
2643 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2644 writeOperand(IV);
2645 Out << "; /* for PHI node */\n";
2646 }
2647 }
2648}
2649
2650void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2651 unsigned Indent) {
2652 if (isGotoCodeNecessary(CurBB, Succ)) {
2653 Out << std::string(Indent, ' ') << " goto ";
2654 writeOperand(Succ);
2655 Out << ";\n";
2656 }
2657}
2658
2659// Branch instruction printing - Avoid printing out a branch to a basic block
2660// that immediately succeeds the current one.
2661//
2662void CWriter::visitBranchInst(BranchInst &I) {
2663
2664 if (I.isConditional()) {
2665 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2666 Out << " if (";
2667 writeOperand(I.getCondition());
2668 Out << ") {\n";
2669
2670 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2671 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2672
2673 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2674 Out << " } else {\n";
2675 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2676 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2677 }
2678 } else {
2679 // First goto not necessary, assume second one is...
2680 Out << " if (!";
2681 writeOperand(I.getCondition());
2682 Out << ") {\n";
2683
2684 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2685 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2686 }
2687
2688 Out << " }\n";
2689 } else {
2690 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2691 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2692 }
2693 Out << "\n";
2694}
2695
2696// PHI nodes get copied into temporary values at the end of predecessor basic
2697// blocks. We now need to copy these temporary values into the REAL value for
2698// the PHI.
2699void CWriter::visitPHINode(PHINode &I) {
2700 writeOperand(&I);
2701 Out << "__PHI_TEMPORARY";
2702}
2703
2704
2705void CWriter::visitBinaryOperator(Instruction &I) {
2706 // binary instructions, shift instructions, setCond instructions.
2707 assert(!isa<PointerType>(I.getType()));
2708
2709 // We must cast the results of binary operations which might be promoted.
2710 bool needsCast = false;
Owen Anderson35b47072009-08-13 21:58:54 +00002711 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2712 (I.getType() == Type::getInt16Ty(I.getContext()))
2713 || (I.getType() == Type::getFloatTy(I.getContext()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714 needsCast = true;
2715 Out << "((";
2716 printType(Out, I.getType(), false);
2717 Out << ")(";
2718 }
2719
2720 // If this is a negation operation, print it out as such. For FP, we don't
2721 // want to print "-0.0 - X".
Owen Anderson76f49252009-07-13 22:18:28 +00002722 if (BinaryOperator::isNeg(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 Out << "-(";
2724 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2725 Out << ")";
Owen Anderson76f49252009-07-13 22:18:28 +00002726 } else if (BinaryOperator::isFNeg(&I)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002727 Out << "-(";
2728 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2729 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002730 } else if (I.getOpcode() == Instruction::FRem) {
2731 // Output a call to fmod/fmodf instead of emitting a%b
Owen Anderson35b47072009-08-13 21:58:54 +00002732 if (I.getType() == Type::getFloatTy(I.getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733 Out << "fmodf(";
Owen Anderson35b47072009-08-13 21:58:54 +00002734 else if (I.getType() == Type::getDoubleTy(I.getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735 Out << "fmod(";
Dale Johannesen137cef62007-09-17 00:38:27 +00002736 else // all 3 flavors of long double
2737 Out << "fmodl(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738 writeOperand(I.getOperand(0));
2739 Out << ", ";
2740 writeOperand(I.getOperand(1));
2741 Out << ")";
2742 } else {
2743
2744 // Write out the cast of the instruction's value back to the proper type
2745 // if necessary.
2746 bool NeedsClosingParens = writeInstructionCast(I);
2747
2748 // Certain instructions require the operand to be forced to a specific type
2749 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2750 // below for operand 1
2751 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2752
2753 switch (I.getOpcode()) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002754 case Instruction::Add:
2755 case Instruction::FAdd: Out << " + "; break;
2756 case Instruction::Sub:
2757 case Instruction::FSub: Out << " - "; break;
2758 case Instruction::Mul:
2759 case Instruction::FMul: Out << " * "; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002760 case Instruction::URem:
2761 case Instruction::SRem:
2762 case Instruction::FRem: Out << " % "; break;
2763 case Instruction::UDiv:
2764 case Instruction::SDiv:
2765 case Instruction::FDiv: Out << " / "; break;
2766 case Instruction::And: Out << " & "; break;
2767 case Instruction::Or: Out << " | "; break;
2768 case Instruction::Xor: Out << " ^ "; break;
2769 case Instruction::Shl : Out << " << "; break;
2770 case Instruction::LShr:
2771 case Instruction::AShr: Out << " >> "; break;
Edwin Török4d9756a2009-07-08 20:53:28 +00002772 default:
2773#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00002774 errs() << "Invalid operator type!" << I;
Edwin Török4d9756a2009-07-08 20:53:28 +00002775#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00002776 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 }
2778
2779 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2780 if (NeedsClosingParens)
2781 Out << "))";
2782 }
2783
2784 if (needsCast) {
2785 Out << "))";
2786 }
2787}
2788
2789void CWriter::visitICmpInst(ICmpInst &I) {
2790 // We must cast the results of icmp which might be promoted.
2791 bool needsCast = false;
2792
2793 // Write out the cast of the instruction's value back to the proper type
2794 // if necessary.
2795 bool NeedsClosingParens = writeInstructionCast(I);
2796
2797 // Certain icmp predicate require the operand to be forced to a specific type
2798 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2799 // below for operand 1
Chris Lattner389c9142007-09-15 06:51:03 +00002800 writeOperandWithCast(I.getOperand(0), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002801
2802 switch (I.getPredicate()) {
2803 case ICmpInst::ICMP_EQ: Out << " == "; break;
2804 case ICmpInst::ICMP_NE: Out << " != "; break;
2805 case ICmpInst::ICMP_ULE:
2806 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2807 case ICmpInst::ICMP_UGE:
2808 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2809 case ICmpInst::ICMP_ULT:
2810 case ICmpInst::ICMP_SLT: Out << " < "; break;
2811 case ICmpInst::ICMP_UGT:
2812 case ICmpInst::ICMP_SGT: Out << " > "; break;
Edwin Török4d9756a2009-07-08 20:53:28 +00002813 default:
2814#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00002815 errs() << "Invalid icmp predicate!" << I;
Edwin Török4d9756a2009-07-08 20:53:28 +00002816#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00002817 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002818 }
2819
Chris Lattner389c9142007-09-15 06:51:03 +00002820 writeOperandWithCast(I.getOperand(1), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002821 if (NeedsClosingParens)
2822 Out << "))";
2823
2824 if (needsCast) {
2825 Out << "))";
2826 }
2827}
2828
2829void CWriter::visitFCmpInst(FCmpInst &I) {
2830 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2831 Out << "0";
2832 return;
2833 }
2834 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2835 Out << "1";
2836 return;
2837 }
2838
2839 const char* op = 0;
2840 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002841 default: llvm_unreachable("Illegal FCmp predicate");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842 case FCmpInst::FCMP_ORD: op = "ord"; break;
2843 case FCmpInst::FCMP_UNO: op = "uno"; break;
2844 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2845 case FCmpInst::FCMP_UNE: op = "une"; break;
2846 case FCmpInst::FCMP_ULT: op = "ult"; break;
2847 case FCmpInst::FCMP_ULE: op = "ule"; break;
2848 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2849 case FCmpInst::FCMP_UGE: op = "uge"; break;
2850 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2851 case FCmpInst::FCMP_ONE: op = "one"; break;
2852 case FCmpInst::FCMP_OLT: op = "olt"; break;
2853 case FCmpInst::FCMP_OLE: op = "ole"; break;
2854 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2855 case FCmpInst::FCMP_OGE: op = "oge"; break;
2856 }
2857
2858 Out << "llvm_fcmp_" << op << "(";
2859 // Write the first operand
2860 writeOperand(I.getOperand(0));
2861 Out << ", ";
2862 // Write the second operand
2863 writeOperand(I.getOperand(1));
2864 Out << ")";
2865}
2866
2867static const char * getFloatBitCastField(const Type *Ty) {
2868 switch (Ty->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00002869 default: llvm_unreachable("Invalid Type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002870 case Type::FloatTyID: return "Float";
2871 case Type::DoubleTyID: return "Double";
2872 case Type::IntegerTyID: {
2873 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2874 if (NumBits <= 32)
2875 return "Int32";
2876 else
2877 return "Int64";
2878 }
2879 }
2880}
2881
2882void CWriter::visitCastInst(CastInst &I) {
2883 const Type *DstTy = I.getType();
2884 const Type *SrcTy = I.getOperand(0)->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885 if (isFPIntBitCast(I)) {
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002886 Out << '(';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887 // These int<->float and long<->double casts need to be handled specially
2888 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2889 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2890 writeOperand(I.getOperand(0));
2891 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2892 << getFloatBitCastField(I.getType());
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002893 Out << ')';
2894 return;
2895 }
2896
2897 Out << '(';
2898 printCast(I.getOpcode(), SrcTy, DstTy);
2899
2900 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
Owen Anderson35b47072009-08-13 21:58:54 +00002901 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2902 I.getOpcode() == Instruction::SExt)
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002903 Out << "0-";
2904
2905 writeOperand(I.getOperand(0));
2906
Owen Anderson35b47072009-08-13 21:58:54 +00002907 if (DstTy == Type::getInt1Ty(I.getContext()) &&
Chris Lattnerd70f5a82008-05-31 09:23:55 +00002908 (I.getOpcode() == Instruction::Trunc ||
2909 I.getOpcode() == Instruction::FPToUI ||
2910 I.getOpcode() == Instruction::FPToSI ||
2911 I.getOpcode() == Instruction::PtrToInt)) {
2912 // Make sure we really get a trunc to bool by anding the operand with 1
2913 Out << "&1u";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002914 }
2915 Out << ')';
2916}
2917
2918void CWriter::visitSelectInst(SelectInst &I) {
2919 Out << "((";
2920 writeOperand(I.getCondition());
2921 Out << ") ? (";
2922 writeOperand(I.getTrueValue());
2923 Out << ") : (";
2924 writeOperand(I.getFalseValue());
2925 Out << "))";
2926}
2927
2928
2929void CWriter::lowerIntrinsics(Function &F) {
2930 // This is used to keep track of intrinsics that get generated to a lowered
2931 // function. We must generate the prototypes before the function body which
2932 // will only be expanded on first use (by the loop below).
2933 std::vector<Function*> prototypesToGen;
2934
2935 // Examine all the instructions in this function to find the intrinsics that
2936 // need to be lowered.
2937 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2938 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2939 if (CallInst *CI = dyn_cast<CallInst>(I++))
2940 if (Function *F = CI->getCalledFunction())
2941 switch (F->getIntrinsicID()) {
2942 case Intrinsic::not_intrinsic:
Andrew Lenharth0531ec52008-02-16 14:46:26 +00002943 case Intrinsic::memory_barrier:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944 case Intrinsic::vastart:
2945 case Intrinsic::vacopy:
2946 case Intrinsic::vaend:
2947 case Intrinsic::returnaddress:
2948 case Intrinsic::frameaddress:
2949 case Intrinsic::setjmp:
2950 case Intrinsic::longjmp:
2951 case Intrinsic::prefetch:
Dale Johannesenc339d8e2007-10-02 17:43:59 +00002952 case Intrinsic::powi:
Chris Lattner6a947cb2008-03-02 08:47:13 +00002953 case Intrinsic::x86_sse_cmp_ss:
2954 case Intrinsic::x86_sse_cmp_ps:
2955 case Intrinsic::x86_sse2_cmp_sd:
2956 case Intrinsic::x86_sse2_cmp_pd:
Chris Lattner709df322008-03-02 08:54:27 +00002957 case Intrinsic::ppc_altivec_lvsl:
Chris Lattner6a947cb2008-03-02 08:47:13 +00002958 // We directly implement these intrinsics
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002959 break;
2960 default:
2961 // If this is an intrinsic that directly corresponds to a GCC
2962 // builtin, we handle it.
2963 const char *BuiltinName = "";
2964#define GET_GCC_BUILTIN_NAME
2965#include "llvm/Intrinsics.gen"
2966#undef GET_GCC_BUILTIN_NAME
2967 // If we handle it, don't lower it.
2968 if (BuiltinName[0]) break;
2969
2970 // All other intrinsic calls we must lower.
2971 Instruction *Before = 0;
2972 if (CI != &BB->front())
2973 Before = prior(BasicBlock::iterator(CI));
2974
2975 IL->LowerIntrinsicCall(CI);
2976 if (Before) { // Move iterator to instruction after call
2977 I = Before; ++I;
2978 } else {
2979 I = BB->begin();
2980 }
2981 // If the intrinsic got lowered to another call, and that call has
2982 // a definition then we need to make sure its prototype is emitted
2983 // before any calls to it.
2984 if (CallInst *Call = dyn_cast<CallInst>(I))
2985 if (Function *NewF = Call->getCalledFunction())
2986 if (!NewF->isDeclaration())
2987 prototypesToGen.push_back(NewF);
2988
2989 break;
2990 }
2991
2992 // We may have collected some prototypes to emit in the loop above.
2993 // Emit them now, before the function that uses them is emitted. But,
2994 // be careful not to emit them twice.
2995 std::vector<Function*>::iterator I = prototypesToGen.begin();
2996 std::vector<Function*>::iterator E = prototypesToGen.end();
2997 for ( ; I != E; ++I) {
2998 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2999 Out << '\n';
3000 printFunctionSignature(*I, true);
3001 Out << ";\n";
3002 }
3003 }
3004}
3005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003006void CWriter::visitCallInst(CallInst &I) {
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003007 if (isa<InlineAsm>(I.getOperand(0)))
3008 return visitInlineAsm(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009
3010 bool WroteCallee = false;
3011
3012 // Handle intrinsic function calls first...
3013 if (Function *F = I.getCalledFunction())
Chris Lattnera74b9182008-03-02 08:29:41 +00003014 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3015 if (visitBuiltinCall(I, ID, WroteCallee))
Andrew Lenharth0531ec52008-02-16 14:46:26 +00003016 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017
3018 Value *Callee = I.getCalledValue();
3019
3020 const PointerType *PTy = cast<PointerType>(Callee->getType());
3021 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3022
3023 // If this is a call to a struct-return function, assign to the first
3024 // parameter instead of passing it to the call.
Devang Pateld222f862008-09-25 21:00:45 +00003025 const AttrListPtr &PAL = I.getAttributes();
Evan Chengb8a072c2008-01-12 18:53:07 +00003026 bool hasByVal = I.hasByValArgument();
Devang Patel949a4b72008-03-03 21:46:28 +00003027 bool isStructRet = I.hasStructRetAttr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028 if (isStructRet) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003029 writeOperandDeref(I.getOperand(1));
Evan Chengf8956382008-01-11 23:10:11 +00003030 Out << " = ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003031 }
3032
3033 if (I.isTailCall()) Out << " /*tail*/ ";
3034
3035 if (!WroteCallee) {
3036 // If this is an indirect call to a struct return function, we need to cast
Evan Chengb8a072c2008-01-12 18:53:07 +00003037 // the pointer. Ditto for indirect calls with byval arguments.
3038 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039
3040 // GCC is a real PITA. It does not permit codegening casts of functions to
3041 // function pointers if they are in a call (it generates a trap instruction
3042 // instead!). We work around this by inserting a cast to void* in between
3043 // the function and the function pointer cast. Unfortunately, we can't just
3044 // form the constant expression here, because the folder will immediately
3045 // nuke it.
3046 //
3047 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3048 // that void* and function pointers have the same size. :( To deal with this
3049 // in the common case, we handle casts where the number of arguments passed
3050 // match exactly.
3051 //
3052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3053 if (CE->isCast())
3054 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3055 NeedsCast = true;
3056 Callee = RF;
3057 }
3058
3059 if (NeedsCast) {
3060 // Ok, just cast the pointer type.
3061 Out << "((";
Evan Chengb8a072c2008-01-12 18:53:07 +00003062 if (isStructRet)
Duncan Sandsf5588dc2007-11-27 13:23:08 +00003063 printStructReturnPointerFunctionType(Out, PAL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003064 cast<PointerType>(I.getCalledValue()->getType()));
Evan Chengb8a072c2008-01-12 18:53:07 +00003065 else if (hasByVal)
3066 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3067 else
3068 printType(Out, I.getCalledValue()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003069 Out << ")(void*)";
3070 }
3071 writeOperand(Callee);
3072 if (NeedsCast) Out << ')';
3073 }
3074
3075 Out << '(';
3076
3077 unsigned NumDeclaredParams = FTy->getNumParams();
3078
3079 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3080 unsigned ArgNo = 0;
3081 if (isStructRet) { // Skip struct return argument.
3082 ++AI;
3083 ++ArgNo;
3084 }
3085
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 bool PrintedArg = false;
Evan Chengf8956382008-01-11 23:10:11 +00003087 for (; AI != AE; ++AI, ++ArgNo) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088 if (PrintedArg) Out << ", ";
3089 if (ArgNo < NumDeclaredParams &&
3090 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3091 Out << '(';
3092 printType(Out, FTy->getParamType(ArgNo),
Devang Pateld222f862008-09-25 21:00:45 +00003093 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003094 Out << ')';
3095 }
Evan Chengf8956382008-01-11 23:10:11 +00003096 // Check if the argument is expected to be passed by value.
Devang Pateld222f862008-09-25 21:00:45 +00003097 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
Chris Lattner8bbc8592008-03-02 08:07:24 +00003098 writeOperandDeref(*AI);
3099 else
3100 writeOperand(*AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101 PrintedArg = true;
3102 }
3103 Out << ')';
3104}
3105
Chris Lattnera74b9182008-03-02 08:29:41 +00003106/// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3107/// if the entire call is handled, return false it it wasn't handled, and
3108/// optionally set 'WroteCallee' if the callee has already been printed out.
3109bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3110 bool &WroteCallee) {
3111 switch (ID) {
3112 default: {
3113 // If this is an intrinsic that directly corresponds to a GCC
3114 // builtin, we emit it here.
3115 const char *BuiltinName = "";
3116 Function *F = I.getCalledFunction();
3117#define GET_GCC_BUILTIN_NAME
3118#include "llvm/Intrinsics.gen"
3119#undef GET_GCC_BUILTIN_NAME
3120 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3121
3122 Out << BuiltinName;
3123 WroteCallee = true;
3124 return false;
3125 }
3126 case Intrinsic::memory_barrier:
Andrew Lenharth5c976182008-03-05 23:41:37 +00003127 Out << "__sync_synchronize()";
Chris Lattnera74b9182008-03-02 08:29:41 +00003128 return true;
3129 case Intrinsic::vastart:
3130 Out << "0; ";
3131
3132 Out << "va_start(*(va_list*)";
3133 writeOperand(I.getOperand(1));
3134 Out << ", ";
3135 // Output the last argument to the enclosing function.
3136 if (I.getParent()->getParent()->arg_empty()) {
Edwin Török4d9756a2009-07-08 20:53:28 +00003137 std::string msg;
3138 raw_string_ostream Msg(msg);
3139 Msg << "The C backend does not currently support zero "
Chris Lattnera74b9182008-03-02 08:29:41 +00003140 << "argument varargs functions, such as '"
Edwin Török4d9756a2009-07-08 20:53:28 +00003141 << I.getParent()->getParent()->getName() << "'!";
3142 llvm_report_error(Msg.str());
Chris Lattnera74b9182008-03-02 08:29:41 +00003143 }
3144 writeOperand(--I.getParent()->getParent()->arg_end());
3145 Out << ')';
3146 return true;
3147 case Intrinsic::vaend:
3148 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3149 Out << "0; va_end(*(va_list*)";
3150 writeOperand(I.getOperand(1));
3151 Out << ')';
3152 } else {
3153 Out << "va_end(*(va_list*)0)";
3154 }
3155 return true;
3156 case Intrinsic::vacopy:
3157 Out << "0; ";
3158 Out << "va_copy(*(va_list*)";
3159 writeOperand(I.getOperand(1));
3160 Out << ", *(va_list*)";
3161 writeOperand(I.getOperand(2));
3162 Out << ')';
3163 return true;
3164 case Intrinsic::returnaddress:
3165 Out << "__builtin_return_address(";
3166 writeOperand(I.getOperand(1));
3167 Out << ')';
3168 return true;
3169 case Intrinsic::frameaddress:
3170 Out << "__builtin_frame_address(";
3171 writeOperand(I.getOperand(1));
3172 Out << ')';
3173 return true;
3174 case Intrinsic::powi:
3175 Out << "__builtin_powi(";
3176 writeOperand(I.getOperand(1));
3177 Out << ", ";
3178 writeOperand(I.getOperand(2));
3179 Out << ')';
3180 return true;
3181 case Intrinsic::setjmp:
3182 Out << "setjmp(*(jmp_buf*)";
3183 writeOperand(I.getOperand(1));
3184 Out << ')';
3185 return true;
3186 case Intrinsic::longjmp:
3187 Out << "longjmp(*(jmp_buf*)";
3188 writeOperand(I.getOperand(1));
3189 Out << ", ";
3190 writeOperand(I.getOperand(2));
3191 Out << ')';
3192 return true;
3193 case Intrinsic::prefetch:
3194 Out << "LLVM_PREFETCH((const void *)";
3195 writeOperand(I.getOperand(1));
3196 Out << ", ";
3197 writeOperand(I.getOperand(2));
3198 Out << ", ";
3199 writeOperand(I.getOperand(3));
3200 Out << ")";
3201 return true;
3202 case Intrinsic::stacksave:
3203 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3204 // to work around GCC bugs (see PR1809).
3205 Out << "0; *((void**)&" << GetValueName(&I)
3206 << ") = __builtin_stack_save()";
3207 return true;
Chris Lattner6a947cb2008-03-02 08:47:13 +00003208 case Intrinsic::x86_sse_cmp_ss:
3209 case Intrinsic::x86_sse_cmp_ps:
3210 case Intrinsic::x86_sse2_cmp_sd:
3211 case Intrinsic::x86_sse2_cmp_pd:
3212 Out << '(';
3213 printType(Out, I.getType());
3214 Out << ')';
3215 // Multiple GCC builtins multiplex onto this intrinsic.
3216 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003217 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
Chris Lattner6a947cb2008-03-02 08:47:13 +00003218 case 0: Out << "__builtin_ia32_cmpeq"; break;
3219 case 1: Out << "__builtin_ia32_cmplt"; break;
3220 case 2: Out << "__builtin_ia32_cmple"; break;
3221 case 3: Out << "__builtin_ia32_cmpunord"; break;
3222 case 4: Out << "__builtin_ia32_cmpneq"; break;
3223 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3224 case 6: Out << "__builtin_ia32_cmpnle"; break;
3225 case 7: Out << "__builtin_ia32_cmpord"; break;
3226 }
3227 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3228 Out << 'p';
3229 else
3230 Out << 's';
3231 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3232 Out << 's';
3233 else
3234 Out << 'd';
3235
3236 Out << "(";
3237 writeOperand(I.getOperand(1));
3238 Out << ", ";
3239 writeOperand(I.getOperand(2));
3240 Out << ")";
3241 return true;
Chris Lattner709df322008-03-02 08:54:27 +00003242 case Intrinsic::ppc_altivec_lvsl:
3243 Out << '(';
3244 printType(Out, I.getType());
3245 Out << ')';
3246 Out << "__builtin_altivec_lvsl(0, (void*)";
3247 writeOperand(I.getOperand(1));
3248 Out << ")";
3249 return true;
Chris Lattnera74b9182008-03-02 08:29:41 +00003250 }
3251}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003252
3253//This converts the llvm constraint string to something gcc is expecting.
3254//TODO: work out platform independent constraints and factor those out
3255// of the per target tables
3256// handle multiple constraint codes
3257std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003258 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3259
Chris Lattner621c44d2009-08-22 20:48:53 +00003260 // Grab the translation table from MCAsmInfo if it exists.
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003261 const MCAsmInfo *TargetAsm;
3262 std::string Triple = TheModule->getTargetTriple();
3263 if (Triple.empty())
3264 Triple = llvm::sys::getHostTriple();
3265
3266 std::string E;
3267 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3268 TargetAsm = Match->createAsmInfo(Triple);
3269 else
3270 return c.Codes[0];
3271
3272 const char *const *table = TargetAsm->getAsmCBE();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273
Daniel Dunbarfe5939f2009-07-15 20:24:03 +00003274 // Search the translation table if it exists.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003275 for (int i = 0; table && table[i]; i += 2)
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003276 if (c.Codes[0] == table[i]) {
3277 delete TargetAsm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 return table[i+1];
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003279 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003280
Daniel Dunbarfe5939f2009-07-15 20:24:03 +00003281 // Default is identity.
Chris Lattner63ab9bb2010-01-17 18:22:35 +00003282 delete TargetAsm;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003283 return c.Codes[0];
3284}
3285
3286//TODO: import logic from AsmPrinter.cpp
3287static std::string gccifyAsm(std::string asmstr) {
3288 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3289 if (asmstr[i] == '\n')
3290 asmstr.replace(i, 1, "\\n");
3291 else if (asmstr[i] == '\t')
3292 asmstr.replace(i, 1, "\\t");
3293 else if (asmstr[i] == '$') {
3294 if (asmstr[i + 1] == '{') {
3295 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3296 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3297 std::string n = "%" +
3298 asmstr.substr(a + 1, b - a - 1) +
3299 asmstr.substr(i + 2, a - i - 2);
3300 asmstr.replace(i, b - i + 1, n);
3301 i += n.size() - 1;
3302 } else
3303 asmstr.replace(i, 1, "%");
3304 }
3305 else if (asmstr[i] == '%')//grr
3306 { asmstr.replace(i, 1, "%%"); ++i;}
3307
3308 return asmstr;
3309}
3310
3311//TODO: assumptions about what consume arguments from the call are likely wrong
3312// handle communitivity
3313void CWriter::visitInlineAsm(CallInst &CI) {
3314 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3315 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003316
3317 std::vector<std::pair<Value*, int> > ResultVals;
Owen Anderson35b47072009-08-13 21:58:54 +00003318 if (CI.getType() == Type::getVoidTy(CI.getContext()))
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003319 ;
3320 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3321 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3322 ResultVals.push_back(std::make_pair(&CI, (int)i));
3323 } else {
3324 ResultVals.push_back(std::make_pair(&CI, -1));
3325 }
3326
Chris Lattnera605a9c2008-06-04 18:03:28 +00003327 // Fix up the asm string for gcc and emit it.
3328 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3329 Out << " :";
3330
3331 unsigned ValueCount = 0;
3332 bool IsFirst = true;
3333
3334 // Convert over all the output constraints.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003335 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
Chris Lattnera605a9c2008-06-04 18:03:28 +00003336 E = Constraints.end(); I != E; ++I) {
3337
3338 if (I->Type != InlineAsm::isOutput) {
3339 ++ValueCount;
3340 continue; // Ignore non-output constraints.
3341 }
3342
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003343 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003344 std::string C = InterpretASMConstraint(*I);
3345 if (C.empty()) continue;
3346
Chris Lattnera605a9c2008-06-04 18:03:28 +00003347 if (!IsFirst) {
Chris Lattner8a3b6e42008-05-22 06:19:37 +00003348 Out << ", ";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003349 IsFirst = false;
3350 }
3351
3352 // Unpack the dest.
3353 Value *DestVal;
3354 int DestValNo = -1;
3355
3356 if (ValueCount < ResultVals.size()) {
3357 DestVal = ResultVals[ValueCount].first;
3358 DestValNo = ResultVals[ValueCount].second;
3359 } else
3360 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3361
3362 if (I->isEarlyClobber)
3363 C = "&"+C;
3364
3365 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3366 if (DestValNo != -1)
3367 Out << ".field" << DestValNo; // Multiple retvals.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003368 Out << ")";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003369 ++ValueCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003370 }
Chris Lattnera605a9c2008-06-04 18:03:28 +00003371
3372
3373 // Convert over all the input constraints.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 Out << "\n :";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003375 IsFirst = true;
3376 ValueCount = 0;
3377 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3378 E = Constraints.end(); I != E; ++I) {
3379 if (I->Type != InlineAsm::isInput) {
3380 ++ValueCount;
3381 continue; // Ignore non-input constraints.
3382 }
3383
3384 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3385 std::string C = InterpretASMConstraint(*I);
3386 if (C.empty()) continue;
3387
3388 if (!IsFirst) {
Chris Lattner5fee1202008-05-22 06:29:38 +00003389 Out << ", ";
Chris Lattnera605a9c2008-06-04 18:03:28 +00003390 IsFirst = false;
3391 }
3392
3393 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3394 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3395
3396 Out << "\"" << C << "\"(";
3397 if (!I->isIndirect)
3398 writeOperand(SrcVal);
3399 else
3400 writeOperandDeref(SrcVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 }
Chris Lattnera605a9c2008-06-04 18:03:28 +00003403
3404 // Convert over the clobber constraints.
3405 IsFirst = true;
Chris Lattnera605a9c2008-06-04 18:03:28 +00003406 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3407 E = Constraints.end(); I != E; ++I) {
3408 if (I->Type != InlineAsm::isClobber)
3409 continue; // Ignore non-input constraints.
3410
3411 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3412 std::string C = InterpretASMConstraint(*I);
3413 if (C.empty()) continue;
3414
3415 if (!IsFirst) {
3416 Out << ", ";
3417 IsFirst = false;
3418 }
3419
3420 Out << '\"' << C << '"';
3421 }
3422
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 Out << ")";
3424}
3425
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003426void CWriter::visitAllocaInst(AllocaInst &I) {
3427 Out << '(';
3428 printType(Out, I.getType());
3429 Out << ") alloca(sizeof(";
3430 printType(Out, I.getType()->getElementType());
3431 Out << ')';
3432 if (I.isArrayAllocation()) {
3433 Out << " * " ;
3434 writeOperand(I.getOperand(0));
3435 }
3436 Out << ')';
3437}
3438
Chris Lattner8bbc8592008-03-02 08:07:24 +00003439void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
Dan Gohmanad831302008-07-24 17:57:48 +00003440 gep_type_iterator E, bool Static) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003441
3442 // If there are no indices, just print out the pointer.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003443 if (I == E) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003444 writeOperand(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003445 return;
3446 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003447
3448 // Find out if the last index is into a vector. If so, we have to print this
3449 // specially. Since vectors can't have elements of indexable type, only the
3450 // last index could possibly be of a vector element.
3451 const VectorType *LastIndexIsVector = 0;
3452 {
3453 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3454 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003456
3457 Out << "(";
3458
3459 // If the last index is into a vector, we can't print it as &a[i][j] because
3460 // we can't index into a vector with j in GCC. Instead, emit this as
3461 // (((float*)&a[i])+j)
3462 if (LastIndexIsVector) {
3463 Out << "((";
3464 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3465 Out << ")(";
3466 }
3467
3468 Out << '&';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469
Chris Lattner8bbc8592008-03-02 08:07:24 +00003470 // If the first index is 0 (very typical) we can do a number of
3471 // simplifications to clean up the code.
3472 Value *FirstOp = I.getOperand();
3473 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3474 // First index isn't simple, print it the hard way.
3475 writeOperand(Ptr);
3476 } else {
3477 ++I; // Skip the zero index.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478
Chris Lattner8bbc8592008-03-02 08:07:24 +00003479 // Okay, emit the first operand. If Ptr is something that is already address
3480 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3481 if (isAddressExposed(Ptr)) {
Dan Gohmanad831302008-07-24 17:57:48 +00003482 writeOperandInternal(Ptr, Static);
Chris Lattner8bbc8592008-03-02 08:07:24 +00003483 } else if (I != E && isa<StructType>(*I)) {
3484 // If we didn't already emit the first operand, see if we can print it as
3485 // P->f instead of "P[0].f"
3486 writeOperand(Ptr);
3487 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3488 ++I; // eat the struct index as well.
3489 } else {
3490 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3491 Out << "(*";
3492 writeOperand(Ptr);
3493 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003494 }
3495 }
3496
Chris Lattner8bbc8592008-03-02 08:07:24 +00003497 for (; I != E; ++I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498 if (isa<StructType>(*I)) {
3499 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
Dan Gohman5d995b02008-06-02 21:30:49 +00003500 } else if (isa<ArrayType>(*I)) {
3501 Out << ".array[";
3502 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3503 Out << ']';
Chris Lattner8bbc8592008-03-02 08:07:24 +00003504 } else if (!isa<VectorType>(*I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 Out << '[';
Chris Lattner7ce1ee42007-09-22 20:16:48 +00003506 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507 Out << ']';
Chris Lattner8bbc8592008-03-02 08:07:24 +00003508 } else {
3509 // If the last index is into a vector, then print it out as "+j)". This
3510 // works with the 'LastIndexIsVector' code above.
3511 if (isa<Constant>(I.getOperand()) &&
3512 cast<Constant>(I.getOperand())->isNullValue()) {
3513 Out << "))"; // avoid "+0".
3514 } else {
3515 Out << ")+(";
3516 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3517 Out << "))";
3518 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519 }
Chris Lattner8bbc8592008-03-02 08:07:24 +00003520 }
3521 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522}
3523
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003524void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3525 bool IsVolatile, unsigned Alignment) {
3526
3527 bool IsUnaligned = Alignment &&
3528 Alignment < TD->getABITypeAlignment(OperandType);
3529
3530 if (!IsUnaligned)
3531 Out << '*';
3532 if (IsVolatile || IsUnaligned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 Out << "((";
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003534 if (IsUnaligned)
3535 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3536 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3537 if (IsUnaligned) {
3538 Out << "; } ";
3539 if (IsVolatile) Out << "volatile ";
3540 Out << "*";
3541 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542 Out << ")";
3543 }
3544
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003545 writeOperand(Operand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003547 if (IsVolatile || IsUnaligned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548 Out << ')';
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003549 if (IsUnaligned)
3550 Out << "->data";
3551 }
3552}
3553
3554void CWriter::visitLoadInst(LoadInst &I) {
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003555 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3556 I.getAlignment());
3557
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558}
3559
3560void CWriter::visitStoreInst(StoreInst &I) {
Lauro Ramos Venancio11048c12008-02-01 21:25:59 +00003561 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3562 I.isVolatile(), I.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003563 Out << " = ";
3564 Value *Operand = I.getOperand(0);
3565 Constant *BitMask = 0;
3566 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3567 if (!ITy->isPowerOf2ByteWidth())
3568 // We have a bit width that doesn't match an even power-of-2 byte
3569 // size. Consequently we must & the value with the type's bit mask
Owen Andersoneacb44d2009-07-24 23:12:02 +00003570 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003571 if (BitMask)
3572 Out << "((";
3573 writeOperand(Operand);
3574 if (BitMask) {
3575 Out << ") & ";
Dan Gohmanad831302008-07-24 17:57:48 +00003576 printConstant(BitMask, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 Out << ")";
3578 }
3579}
3580
3581void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner8bbc8592008-03-02 08:07:24 +00003582 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
Dan Gohmanad831302008-07-24 17:57:48 +00003583 gep_type_end(I), false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003584}
3585
3586void CWriter::visitVAArgInst(VAArgInst &I) {
3587 Out << "va_arg(*(va_list*)";
3588 writeOperand(I.getOperand(0));
3589 Out << ", ";
3590 printType(Out, I.getType());
3591 Out << ");\n ";
3592}
3593
Chris Lattnerf41a7942008-03-02 03:52:39 +00003594void CWriter::visitInsertElementInst(InsertElementInst &I) {
3595 const Type *EltTy = I.getType()->getElementType();
3596 writeOperand(I.getOperand(0));
3597 Out << ";\n ";
3598 Out << "((";
3599 printType(Out, PointerType::getUnqual(EltTy));
3600 Out << ")(&" << GetValueName(&I) << "))[";
Chris Lattnerf41a7942008-03-02 03:52:39 +00003601 writeOperand(I.getOperand(2));
Chris Lattner09418362008-03-02 08:10:16 +00003602 Out << "] = (";
3603 writeOperand(I.getOperand(1));
Chris Lattnerf41a7942008-03-02 03:52:39 +00003604 Out << ")";
3605}
3606
Chris Lattnera5f0bc02008-03-02 03:57:08 +00003607void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3608 // We know that our operand is not inlined.
3609 Out << "((";
3610 const Type *EltTy =
3611 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3612 printType(Out, PointerType::getUnqual(EltTy));
3613 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3614 writeOperand(I.getOperand(1));
3615 Out << "]";
3616}
3617
Chris Lattnerf858a042008-03-02 05:41:07 +00003618void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3619 Out << "(";
3620 printType(Out, SVI.getType());
3621 Out << "){ ";
3622 const VectorType *VT = SVI.getType();
3623 unsigned NumElts = VT->getNumElements();
3624 const Type *EltTy = VT->getElementType();
3625
3626 for (unsigned i = 0; i != NumElts; ++i) {
3627 if (i) Out << ", ";
3628 int SrcVal = SVI.getMaskValue(i);
3629 if ((unsigned)SrcVal >= NumElts*2) {
3630 Out << " 0/*undef*/ ";
3631 } else {
3632 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3633 if (isa<Instruction>(Op)) {
3634 // Do an extractelement of this value from the appropriate input.
3635 Out << "((";
3636 printType(Out, PointerType::getUnqual(EltTy));
3637 Out << ")(&" << GetValueName(Op)
Duncan Sandsf6890712008-05-27 11:50:51 +00003638 << "))[" << (SrcVal & (NumElts-1)) << "]";
Chris Lattnerf858a042008-03-02 05:41:07 +00003639 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3640 Out << "0";
3641 } else {
Duncan Sandsf6890712008-05-27 11:50:51 +00003642 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
Dan Gohmanad831302008-07-24 17:57:48 +00003643 (NumElts-1)),
3644 false);
Chris Lattnerf858a042008-03-02 05:41:07 +00003645 }
3646 }
3647 }
3648 Out << "}";
3649}
Chris Lattnera5f0bc02008-03-02 03:57:08 +00003650
Dan Gohman5d995b02008-06-02 21:30:49 +00003651void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3652 // Start by copying the entire aggregate value into the result variable.
3653 writeOperand(IVI.getOperand(0));
3654 Out << ";\n ";
3655
3656 // Then do the insert to update the field.
3657 Out << GetValueName(&IVI);
3658 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3659 i != e; ++i) {
3660 const Type *IndexedTy =
3661 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3662 if (isa<ArrayType>(IndexedTy))
3663 Out << ".array[" << *i << "]";
3664 else
3665 Out << ".field" << *i;
3666 }
3667 Out << " = ";
3668 writeOperand(IVI.getOperand(1));
3669}
3670
3671void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3672 Out << "(";
3673 if (isa<UndefValue>(EVI.getOperand(0))) {
3674 Out << "(";
3675 printType(Out, EVI.getType());
3676 Out << ") 0/*UNDEF*/";
3677 } else {
3678 Out << GetValueName(EVI.getOperand(0));
3679 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3680 i != e; ++i) {
3681 const Type *IndexedTy =
3682 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3683 if (isa<ArrayType>(IndexedTy))
3684 Out << ".array[" << *i << "]";
3685 else
3686 Out << ".field" << *i;
3687 }
3688 }
3689 Out << ")";
3690}
3691
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692//===----------------------------------------------------------------------===//
3693// External Interface declaration
3694//===----------------------------------------------------------------------===//
3695
3696bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene302008d2009-07-14 20:18:05 +00003697 formatted_raw_ostream &o,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 CodeGenFileType FileType,
Bill Wendling5ed22ac2009-04-29 23:29:43 +00003699 CodeGenOpt::Level OptLevel) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003700 if (FileType != TargetMachine::AssemblyFile) return true;
3701
Gordon Henriksendf87fdc2008-01-07 01:30:38 +00003702 PM.add(createGCLoweringPass());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003703 PM.add(createLowerInvokePass());
3704 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3705 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3706 PM.add(new CWriter(o));
Gordon Henriksen1aed5992008-08-17 18:44:35 +00003707 PM.add(createGCInfoDeleter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003708 return false;
3709}