1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
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"
21 #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"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Analysis/ConstantsScanner.h"
31 #include "llvm/Analysis/FindUsedTypes.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstVisitor.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/System/Host.h"
50 #include "llvm/Config/config.h"
55 extern "C" void LLVMInitializeCBackendTarget() {
56 // Register the target.
57 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
61 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
62 /// any unnamed structure types that are used by the program, and merges
63 /// external functions with the same name.
65 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
68 CBackendNameAllUsedStructsAndMergeFunctions()
70 void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<FindUsedTypes>();
74 virtual const char *getPassName() const {
75 return "C backend type canonicalizer";
78 virtual bool runOnModule(Module &M);
81 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
83 /// CWriter - This class is the main chunk of code that converts an LLVM
84 /// module to a C translation unit.
85 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
86 formatted_raw_ostream &Out;
87 IntrinsicLowering *IL;
90 const Module *TheModule;
91 const MCAsmInfo* TAsm;
93 std::map<const Type *, std::string> TypeNames;
94 std::map<const ConstantFP *, unsigned> FPConstantMap;
95 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
96 std::set<const Argument*> ByValParams;
98 unsigned OpaqueCounter;
99 DenseMap<const Value*, unsigned> AnonValueNumbers;
100 unsigned NextAnonValueNumber;
104 explicit CWriter(formatted_raw_ostream &o)
105 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
106 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
110 virtual const char *getPassName() const { return "C backend"; }
112 void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.addRequired<LoopInfo>();
114 AU.setPreservesAll();
117 virtual bool doInitialization(Module &M);
119 bool runOnFunction(Function &F) {
120 // Do not codegen any 'available_externally' functions at all, they have
121 // definitions outside the translation unit.
122 if (F.hasAvailableExternallyLinkage())
125 LI = &getAnalysis<LoopInfo>();
127 // Get rid of intrinsics we can't handle.
130 // Output all floating point constants that cannot be printed accurately.
131 printFloatingPointConstants(F);
137 virtual bool doFinalization(Module &M) {
142 FPConstantMap.clear();
145 intrinsicPrototypesAlreadyGenerated.clear();
149 raw_ostream &printType(formatted_raw_ostream &Out,
151 bool isSigned = false,
152 const std::string &VariableName = "",
153 bool IgnoreName = false,
154 const AttrListPtr &PAL = AttrListPtr());
155 std::ostream &printType(std::ostream &Out, const Type *Ty,
156 bool isSigned = false,
157 const std::string &VariableName = "",
158 bool IgnoreName = false,
159 const AttrListPtr &PAL = AttrListPtr());
160 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
163 const std::string &NameSoFar = "");
164 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
166 const std::string &NameSoFar = "");
168 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
169 const AttrListPtr &PAL,
170 const PointerType *Ty);
172 /// writeOperandDeref - Print the result of dereferencing the specified
173 /// operand with '*'. This is equivalent to printing '*' then using
174 /// writeOperand, but avoids excess syntax in some cases.
175 void writeOperandDeref(Value *Operand) {
176 if (isAddressExposed(Operand)) {
177 // Already something with an address exposed.
178 writeOperandInternal(Operand);
181 writeOperand(Operand);
186 void writeOperand(Value *Operand, bool Static = false);
187 void writeInstComputationInline(Instruction &I);
188 void writeOperandInternal(Value *Operand, bool Static = false);
189 void writeOperandWithCast(Value* Operand, unsigned Opcode);
190 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
191 bool writeInstructionCast(const Instruction &I);
193 void writeMemoryAccess(Value *Operand, const Type *OperandType,
194 bool IsVolatile, unsigned Alignment);
197 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
199 void lowerIntrinsics(Function &F);
201 void printModule(Module *M);
202 void printModuleTypes(const TypeSymbolTable &ST);
203 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
204 void printFloatingPointConstants(Function &F);
205 void printFloatingPointConstants(const Constant *C);
206 void printFunctionSignature(const Function *F, bool Prototype);
208 void printFunction(Function &);
209 void printBasicBlock(BasicBlock *BB);
210 void printLoop(Loop *L);
212 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
213 void printConstant(Constant *CPV, bool Static);
214 void printConstantWithCast(Constant *CPV, unsigned Opcode);
215 bool printConstExprCast(const ConstantExpr *CE, bool Static);
216 void printConstantArray(ConstantArray *CPA, bool Static);
217 void printConstantVector(ConstantVector *CV, bool Static);
219 /// isAddressExposed - Return true if the specified value's name needs to
220 /// have its address taken in order to get a C value of the correct type.
221 /// This happens for global variables, byval parameters, and direct allocas.
222 bool isAddressExposed(const Value *V) const {
223 if (const Argument *A = dyn_cast<Argument>(V))
224 return ByValParams.count(A);
225 return isa<GlobalVariable>(V) || isDirectAlloca(V);
228 // isInlinableInst - Attempt to inline instructions into their uses to build
229 // trees as much as possible. To do this, we have to consistently decide
230 // what is acceptable to inline, so that variable declarations don't get
231 // printed and an extra copy of the expr is not emitted.
233 static bool isInlinableInst(const Instruction &I) {
234 // Always inline cmp instructions, even if they are shared by multiple
235 // expressions. GCC generates horrible code if we don't.
239 // Must be an expression, must be used exactly once. If it is dead, we
240 // emit it inline where it would go.
241 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
242 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
243 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
244 isa<InsertValueInst>(I))
245 // Don't inline a load across a store or other bad things!
248 // Must not be used in inline asm, extractelement, or shufflevector.
250 const Instruction &User = cast<Instruction>(*I.use_back());
251 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
252 isa<ShuffleVectorInst>(User))
256 // Only inline instruction it if it's use is in the same BB as the inst.
257 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
260 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
261 // variables which are accessed with the & operator. This causes GCC to
262 // generate significantly better code than to emit alloca calls directly.
264 static const AllocaInst *isDirectAlloca(const Value *V) {
265 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
266 if (!AI) return false;
267 if (AI->isArrayAllocation())
268 return 0; // FIXME: we can also inline fixed size array allocas!
269 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
274 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
275 static bool isInlineAsm(const Instruction& I) {
276 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
281 // Instruction visitation functions
282 friend class InstVisitor<CWriter>;
284 void visitReturnInst(ReturnInst &I);
285 void visitBranchInst(BranchInst &I);
286 void visitSwitchInst(SwitchInst &I);
287 void visitIndirectBrInst(IndirectBrInst &I);
288 void visitInvokeInst(InvokeInst &I) {
289 llvm_unreachable("Lowerinvoke pass didn't work!");
292 void visitUnwindInst(UnwindInst &I) {
293 llvm_unreachable("Lowerinvoke pass didn't work!");
295 void visitUnreachableInst(UnreachableInst &I);
297 void visitPHINode(PHINode &I);
298 void visitBinaryOperator(Instruction &I);
299 void visitICmpInst(ICmpInst &I);
300 void visitFCmpInst(FCmpInst &I);
302 void visitCastInst (CastInst &I);
303 void visitSelectInst(SelectInst &I);
304 void visitCallInst (CallInst &I);
305 void visitInlineAsm(CallInst &I);
306 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
308 void visitAllocaInst(AllocaInst &I);
309 void visitLoadInst (LoadInst &I);
310 void visitStoreInst (StoreInst &I);
311 void visitGetElementPtrInst(GetElementPtrInst &I);
312 void visitVAArgInst (VAArgInst &I);
314 void visitInsertElementInst(InsertElementInst &I);
315 void visitExtractElementInst(ExtractElementInst &I);
316 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
318 void visitInsertValueInst(InsertValueInst &I);
319 void visitExtractValueInst(ExtractValueInst &I);
321 void visitInstruction(Instruction &I) {
323 errs() << "C Writer does not know about " << I;
328 void outputLValue(Instruction *I) {
329 Out << " " << GetValueName(I) << " = ";
332 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
333 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
334 BasicBlock *Successor, unsigned Indent);
335 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
337 void printGEPExpression(Value *Ptr, gep_type_iterator I,
338 gep_type_iterator E, bool Static);
340 std::string GetValueName(const Value *Operand);
344 char CWriter::ID = 0;
347 static std::string Mangle(const std::string &S) {
349 raw_string_ostream OS(Result);
350 MCSymbol::printMangledName(S, OS, 0);
355 /// This method inserts names for any unnamed structure types that are used by
356 /// the program, and removes names from structure types that are not used by the
359 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
360 // Get a set of types that are used by the program...
361 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
363 // Loop over the module symbol table, removing types from UT that are
364 // already named, and removing names for types that are not used.
366 TypeSymbolTable &TST = M.getTypeSymbolTable();
367 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
369 TypeSymbolTable::iterator I = TI++;
371 // If this isn't a struct or array type, remove it from our set of types
372 // to name. This simplifies emission later.
373 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
374 !isa<ArrayType>(I->second)) {
377 // If this is not used, remove it from the symbol table.
378 std::set<const Type *>::iterator UTI = UT.find(I->second);
382 UT.erase(UTI); // Only keep one name for this type.
386 // UT now contains types that are not named. Loop over it, naming
389 bool Changed = false;
390 unsigned RenameCounter = 0;
391 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
393 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
394 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
400 // Loop over all external functions and globals. If we have two with
401 // identical names, merge them.
402 // FIXME: This code should disappear when we don't allow values with the same
403 // names when they have different types!
404 std::map<std::string, GlobalValue*> ExtSymbols;
405 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
407 if (GV->isDeclaration() && GV->hasName()) {
408 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
409 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
411 // Found a conflict, replace this global with the previous one.
412 GlobalValue *OldGV = X.first->second;
413 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
414 GV->eraseFromParent();
419 // Do the same for globals.
420 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
422 GlobalVariable *GV = I++;
423 if (GV->isDeclaration() && GV->hasName()) {
424 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
425 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
427 // Found a conflict, replace this global with the previous one.
428 GlobalValue *OldGV = X.first->second;
429 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
430 GV->eraseFromParent();
439 /// printStructReturnPointerFunctionType - This is like printType for a struct
440 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
441 /// print it as "Struct (*)(...)", for struct return functions.
442 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
443 const AttrListPtr &PAL,
444 const PointerType *TheTy) {
445 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
446 std::stringstream FunctionInnards;
447 FunctionInnards << " (*) (";
448 bool PrintedType = false;
450 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
451 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
453 for (++I, ++Idx; I != E; ++I, ++Idx) {
455 FunctionInnards << ", ";
456 const Type *ArgTy = *I;
457 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
458 assert(isa<PointerType>(ArgTy));
459 ArgTy = cast<PointerType>(ArgTy)->getElementType();
461 printType(FunctionInnards, ArgTy,
462 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
465 if (FTy->isVarArg()) {
467 FunctionInnards << ", ...";
468 } else if (!PrintedType) {
469 FunctionInnards << "void";
471 FunctionInnards << ')';
472 std::string tstr = FunctionInnards.str();
473 printType(Out, RetTy,
474 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
478 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
480 const std::string &NameSoFar) {
481 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
482 "Invalid type for printSimpleType");
483 switch (Ty->getTypeID()) {
484 case Type::VoidTyID: return Out << "void " << NameSoFar;
485 case Type::IntegerTyID: {
486 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
488 return Out << "bool " << NameSoFar;
489 else if (NumBits <= 8)
490 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
491 else if (NumBits <= 16)
492 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
493 else if (NumBits <= 32)
494 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
495 else if (NumBits <= 64)
496 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
498 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
499 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
502 case Type::FloatTyID: return Out << "float " << NameSoFar;
503 case Type::DoubleTyID: return Out << "double " << NameSoFar;
504 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
505 // present matches host 'long double'.
506 case Type::X86_FP80TyID:
507 case Type::PPC_FP128TyID:
508 case Type::FP128TyID: return Out << "long double " << NameSoFar;
510 case Type::VectorTyID: {
511 const VectorType *VTy = cast<VectorType>(Ty);
512 return printSimpleType(Out, VTy->getElementType(), isSigned,
513 " __attribute__((vector_size(" +
514 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
519 errs() << "Unknown primitive type: " << *Ty << "\n";
526 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
527 const std::string &NameSoFar) {
528 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
529 "Invalid type for printSimpleType");
530 switch (Ty->getTypeID()) {
531 case Type::VoidTyID: return Out << "void " << NameSoFar;
532 case Type::IntegerTyID: {
533 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
535 return Out << "bool " << NameSoFar;
536 else if (NumBits <= 8)
537 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
538 else if (NumBits <= 16)
539 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
540 else if (NumBits <= 32)
541 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
542 else if (NumBits <= 64)
543 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
545 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
546 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
549 case Type::FloatTyID: return Out << "float " << NameSoFar;
550 case Type::DoubleTyID: return Out << "double " << NameSoFar;
551 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
552 // present matches host 'long double'.
553 case Type::X86_FP80TyID:
554 case Type::PPC_FP128TyID:
555 case Type::FP128TyID: return Out << "long double " << NameSoFar;
557 case Type::VectorTyID: {
558 const VectorType *VTy = cast<VectorType>(Ty);
559 return printSimpleType(Out, VTy->getElementType(), isSigned,
560 " __attribute__((vector_size(" +
561 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
566 errs() << "Unknown primitive type: " << *Ty << "\n";
572 // Pass the Type* and the variable name and this prints out the variable
575 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
577 bool isSigned, const std::string &NameSoFar,
578 bool IgnoreName, const AttrListPtr &PAL) {
579 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
580 printSimpleType(Out, Ty, isSigned, NameSoFar);
584 // Check to see if the type is named.
585 if (!IgnoreName || isa<OpaqueType>(Ty)) {
586 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
587 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
590 switch (Ty->getTypeID()) {
591 case Type::FunctionTyID: {
592 const FunctionType *FTy = cast<FunctionType>(Ty);
593 std::stringstream FunctionInnards;
594 FunctionInnards << " (" << NameSoFar << ") (";
596 for (FunctionType::param_iterator I = FTy->param_begin(),
597 E = FTy->param_end(); I != E; ++I) {
598 const Type *ArgTy = *I;
599 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
600 assert(isa<PointerType>(ArgTy));
601 ArgTy = cast<PointerType>(ArgTy)->getElementType();
603 if (I != FTy->param_begin())
604 FunctionInnards << ", ";
605 printType(FunctionInnards, ArgTy,
606 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
609 if (FTy->isVarArg()) {
610 if (FTy->getNumParams())
611 FunctionInnards << ", ...";
612 } else if (!FTy->getNumParams()) {
613 FunctionInnards << "void";
615 FunctionInnards << ')';
616 std::string tstr = FunctionInnards.str();
617 printType(Out, FTy->getReturnType(),
618 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
621 case Type::StructTyID: {
622 const StructType *STy = cast<StructType>(Ty);
623 Out << NameSoFar + " {\n";
625 for (StructType::element_iterator I = STy->element_begin(),
626 E = STy->element_end(); I != E; ++I) {
628 printType(Out, *I, false, "field" + utostr(Idx++));
633 Out << " __attribute__ ((packed))";
637 case Type::PointerTyID: {
638 const PointerType *PTy = cast<PointerType>(Ty);
639 std::string ptrName = "*" + NameSoFar;
641 if (isa<ArrayType>(PTy->getElementType()) ||
642 isa<VectorType>(PTy->getElementType()))
643 ptrName = "(" + ptrName + ")";
646 // Must be a function ptr cast!
647 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
648 return printType(Out, PTy->getElementType(), false, ptrName);
651 case Type::ArrayTyID: {
652 const ArrayType *ATy = cast<ArrayType>(Ty);
653 unsigned NumElements = ATy->getNumElements();
654 if (NumElements == 0) NumElements = 1;
655 // Arrays are wrapped in structs to allow them to have normal
656 // value semantics (avoiding the array "decay").
657 Out << NameSoFar << " { ";
658 printType(Out, ATy->getElementType(), false,
659 "array[" + utostr(NumElements) + "]");
663 case Type::OpaqueTyID: {
664 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
665 assert(TypeNames.find(Ty) == TypeNames.end());
666 TypeNames[Ty] = TyName;
667 return Out << TyName << ' ' << NameSoFar;
670 llvm_unreachable("Unhandled case in getTypeProps!");
676 // Pass the Type* and the variable name and this prints out the variable
679 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
680 bool isSigned, const std::string &NameSoFar,
681 bool IgnoreName, const AttrListPtr &PAL) {
682 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
683 printSimpleType(Out, Ty, isSigned, NameSoFar);
687 // Check to see if the type is named.
688 if (!IgnoreName || isa<OpaqueType>(Ty)) {
689 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
690 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
693 switch (Ty->getTypeID()) {
694 case Type::FunctionTyID: {
695 const FunctionType *FTy = cast<FunctionType>(Ty);
696 std::stringstream FunctionInnards;
697 FunctionInnards << " (" << NameSoFar << ") (";
699 for (FunctionType::param_iterator I = FTy->param_begin(),
700 E = FTy->param_end(); I != E; ++I) {
701 const Type *ArgTy = *I;
702 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
703 assert(isa<PointerType>(ArgTy));
704 ArgTy = cast<PointerType>(ArgTy)->getElementType();
706 if (I != FTy->param_begin())
707 FunctionInnards << ", ";
708 printType(FunctionInnards, ArgTy,
709 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
712 if (FTy->isVarArg()) {
713 if (FTy->getNumParams())
714 FunctionInnards << ", ...";
715 } else if (!FTy->getNumParams()) {
716 FunctionInnards << "void";
718 FunctionInnards << ')';
719 std::string tstr = FunctionInnards.str();
720 printType(Out, FTy->getReturnType(),
721 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
724 case Type::StructTyID: {
725 const StructType *STy = cast<StructType>(Ty);
726 Out << NameSoFar + " {\n";
728 for (StructType::element_iterator I = STy->element_begin(),
729 E = STy->element_end(); I != E; ++I) {
731 printType(Out, *I, false, "field" + utostr(Idx++));
736 Out << " __attribute__ ((packed))";
740 case Type::PointerTyID: {
741 const PointerType *PTy = cast<PointerType>(Ty);
742 std::string ptrName = "*" + NameSoFar;
744 if (isa<ArrayType>(PTy->getElementType()) ||
745 isa<VectorType>(PTy->getElementType()))
746 ptrName = "(" + ptrName + ")";
749 // Must be a function ptr cast!
750 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
751 return printType(Out, PTy->getElementType(), false, ptrName);
754 case Type::ArrayTyID: {
755 const ArrayType *ATy = cast<ArrayType>(Ty);
756 unsigned NumElements = ATy->getNumElements();
757 if (NumElements == 0) NumElements = 1;
758 // Arrays are wrapped in structs to allow them to have normal
759 // value semantics (avoiding the array "decay").
760 Out << NameSoFar << " { ";
761 printType(Out, ATy->getElementType(), false,
762 "array[" + utostr(NumElements) + "]");
766 case Type::OpaqueTyID: {
767 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
768 assert(TypeNames.find(Ty) == TypeNames.end());
769 TypeNames[Ty] = TyName;
770 return Out << TyName << ' ' << NameSoFar;
773 llvm_unreachable("Unhandled case in getTypeProps!");
779 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
781 // As a special case, print the array as a string if it is an array of
782 // ubytes or an array of sbytes with positive values.
784 const Type *ETy = CPA->getType()->getElementType();
785 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
786 ETy == Type::getInt8Ty(CPA->getContext()));
788 // Make sure the last character is a null char, as automatically added by C
789 if (isString && (CPA->getNumOperands() == 0 ||
790 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
795 // Keep track of whether the last number was a hexadecimal escape
796 bool LastWasHex = false;
798 // Do not include the last character, which we know is null
799 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
800 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
802 // Print it out literally if it is a printable character. The only thing
803 // to be careful about is when the last letter output was a hex escape
804 // code, in which case we have to be careful not to print out hex digits
805 // explicitly (the C compiler thinks it is a continuation of the previous
806 // character, sheesh...)
808 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
810 if (C == '"' || C == '\\')
811 Out << "\\" << (char)C;
817 case '\n': Out << "\\n"; break;
818 case '\t': Out << "\\t"; break;
819 case '\r': Out << "\\r"; break;
820 case '\v': Out << "\\v"; break;
821 case '\a': Out << "\\a"; break;
822 case '\"': Out << "\\\""; break;
823 case '\'': Out << "\\\'"; break;
826 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
827 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
836 if (CPA->getNumOperands()) {
838 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
839 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
841 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
848 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
850 if (CP->getNumOperands()) {
852 printConstant(cast<Constant>(CP->getOperand(0)), Static);
853 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
855 printConstant(cast<Constant>(CP->getOperand(i)), Static);
861 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
862 // textually as a double (rather than as a reference to a stack-allocated
863 // variable). We decide this by converting CFP to a string and back into a
864 // double, and then checking whether the conversion results in a bit-equal
865 // double to the original value of CFP. This depends on us and the target C
866 // compiler agreeing on the conversion process (which is pretty likely since we
867 // only deal in IEEE FP).
869 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
871 // Do long doubles in hex for now.
872 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
873 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
875 APFloat APF = APFloat(CFP->getValueAPF()); // copy
876 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
877 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
878 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
880 sprintf(Buffer, "%a", APF.convertToDouble());
881 if (!strncmp(Buffer, "0x", 2) ||
882 !strncmp(Buffer, "-0x", 3) ||
883 !strncmp(Buffer, "+0x", 3))
884 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
887 std::string StrVal = ftostr(APF);
889 while (StrVal[0] == ' ')
890 StrVal.erase(StrVal.begin());
892 // Check to make sure that the stringized number is not some string like "Inf"
893 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
894 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
895 ((StrVal[0] == '-' || StrVal[0] == '+') &&
896 (StrVal[1] >= '0' && StrVal[1] <= '9')))
897 // Reparse stringized version!
898 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
903 /// Print out the casting for a cast operation. This does the double casting
904 /// necessary for conversion to the destination type, if necessary.
905 /// @brief Print a cast
906 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
907 // Print the destination type cast
909 case Instruction::UIToFP:
910 case Instruction::SIToFP:
911 case Instruction::IntToPtr:
912 case Instruction::Trunc:
913 case Instruction::BitCast:
914 case Instruction::FPExt:
915 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
917 printType(Out, DstTy);
920 case Instruction::ZExt:
921 case Instruction::PtrToInt:
922 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
924 printSimpleType(Out, DstTy, false);
927 case Instruction::SExt:
928 case Instruction::FPToSI: // For these, make sure we get a signed dest
930 printSimpleType(Out, DstTy, true);
934 llvm_unreachable("Invalid cast opcode");
937 // Print the source type cast
939 case Instruction::UIToFP:
940 case Instruction::ZExt:
942 printSimpleType(Out, SrcTy, false);
945 case Instruction::SIToFP:
946 case Instruction::SExt:
948 printSimpleType(Out, SrcTy, true);
951 case Instruction::IntToPtr:
952 case Instruction::PtrToInt:
953 // Avoid "cast to pointer from integer of different size" warnings
954 Out << "(unsigned long)";
956 case Instruction::Trunc:
957 case Instruction::BitCast:
958 case Instruction::FPExt:
959 case Instruction::FPTrunc:
960 case Instruction::FPToSI:
961 case Instruction::FPToUI:
962 break; // These don't need a source cast.
964 llvm_unreachable("Invalid cast opcode");
969 // printConstant - The LLVM Constant to C Constant converter.
970 void CWriter::printConstant(Constant *CPV, bool Static) {
971 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
972 switch (CE->getOpcode()) {
973 case Instruction::Trunc:
974 case Instruction::ZExt:
975 case Instruction::SExt:
976 case Instruction::FPTrunc:
977 case Instruction::FPExt:
978 case Instruction::UIToFP:
979 case Instruction::SIToFP:
980 case Instruction::FPToUI:
981 case Instruction::FPToSI:
982 case Instruction::PtrToInt:
983 case Instruction::IntToPtr:
984 case Instruction::BitCast:
986 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
987 if (CE->getOpcode() == Instruction::SExt &&
988 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
989 // Make sure we really sext from bool here by subtracting from 0
992 printConstant(CE->getOperand(0), Static);
993 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
994 (CE->getOpcode() == Instruction::Trunc ||
995 CE->getOpcode() == Instruction::FPToUI ||
996 CE->getOpcode() == Instruction::FPToSI ||
997 CE->getOpcode() == Instruction::PtrToInt)) {
998 // Make sure we really truncate to bool here by anding with 1
1004 case Instruction::GetElementPtr:
1006 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1007 gep_type_end(CPV), Static);
1010 case Instruction::Select:
1012 printConstant(CE->getOperand(0), Static);
1014 printConstant(CE->getOperand(1), Static);
1016 printConstant(CE->getOperand(2), Static);
1019 case Instruction::Add:
1020 case Instruction::FAdd:
1021 case Instruction::Sub:
1022 case Instruction::FSub:
1023 case Instruction::Mul:
1024 case Instruction::FMul:
1025 case Instruction::SDiv:
1026 case Instruction::UDiv:
1027 case Instruction::FDiv:
1028 case Instruction::URem:
1029 case Instruction::SRem:
1030 case Instruction::FRem:
1031 case Instruction::And:
1032 case Instruction::Or:
1033 case Instruction::Xor:
1034 case Instruction::ICmp:
1035 case Instruction::Shl:
1036 case Instruction::LShr:
1037 case Instruction::AShr:
1040 bool NeedsClosingParens = printConstExprCast(CE, Static);
1041 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1042 switch (CE->getOpcode()) {
1043 case Instruction::Add:
1044 case Instruction::FAdd: Out << " + "; break;
1045 case Instruction::Sub:
1046 case Instruction::FSub: Out << " - "; break;
1047 case Instruction::Mul:
1048 case Instruction::FMul: Out << " * "; break;
1049 case Instruction::URem:
1050 case Instruction::SRem:
1051 case Instruction::FRem: Out << " % "; break;
1052 case Instruction::UDiv:
1053 case Instruction::SDiv:
1054 case Instruction::FDiv: Out << " / "; break;
1055 case Instruction::And: Out << " & "; break;
1056 case Instruction::Or: Out << " | "; break;
1057 case Instruction::Xor: Out << " ^ "; break;
1058 case Instruction::Shl: Out << " << "; break;
1059 case Instruction::LShr:
1060 case Instruction::AShr: Out << " >> "; break;
1061 case Instruction::ICmp:
1062 switch (CE->getPredicate()) {
1063 case ICmpInst::ICMP_EQ: Out << " == "; break;
1064 case ICmpInst::ICMP_NE: Out << " != "; break;
1065 case ICmpInst::ICMP_SLT:
1066 case ICmpInst::ICMP_ULT: Out << " < "; break;
1067 case ICmpInst::ICMP_SLE:
1068 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1069 case ICmpInst::ICMP_SGT:
1070 case ICmpInst::ICMP_UGT: Out << " > "; break;
1071 case ICmpInst::ICMP_SGE:
1072 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1073 default: llvm_unreachable("Illegal ICmp predicate");
1076 default: llvm_unreachable("Illegal opcode here!");
1078 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1079 if (NeedsClosingParens)
1084 case Instruction::FCmp: {
1086 bool NeedsClosingParens = printConstExprCast(CE, Static);
1087 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1089 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1093 switch (CE->getPredicate()) {
1094 default: llvm_unreachable("Illegal FCmp predicate");
1095 case FCmpInst::FCMP_ORD: op = "ord"; break;
1096 case FCmpInst::FCMP_UNO: op = "uno"; break;
1097 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1098 case FCmpInst::FCMP_UNE: op = "une"; break;
1099 case FCmpInst::FCMP_ULT: op = "ult"; break;
1100 case FCmpInst::FCMP_ULE: op = "ule"; break;
1101 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1102 case FCmpInst::FCMP_UGE: op = "uge"; break;
1103 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1104 case FCmpInst::FCMP_ONE: op = "one"; break;
1105 case FCmpInst::FCMP_OLT: op = "olt"; break;
1106 case FCmpInst::FCMP_OLE: op = "ole"; break;
1107 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1108 case FCmpInst::FCMP_OGE: op = "oge"; break;
1110 Out << "llvm_fcmp_" << op << "(";
1111 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1113 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1116 if (NeedsClosingParens)
1123 errs() << "CWriter Error: Unhandled constant expression: "
1126 llvm_unreachable(0);
1128 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1130 printType(Out, CPV->getType()); // sign doesn't matter
1131 Out << ")/*UNDEF*/";
1132 if (!isa<VectorType>(CPV->getType())) {
1140 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1141 const Type* Ty = CI->getType();
1142 if (Ty == Type::getInt1Ty(CPV->getContext()))
1143 Out << (CI->getZExtValue() ? '1' : '0');
1144 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1145 Out << CI->getZExtValue() << 'u';
1146 else if (Ty->getPrimitiveSizeInBits() > 32)
1147 Out << CI->getZExtValue() << "ull";
1150 printSimpleType(Out, Ty, false) << ')';
1151 if (CI->isMinValue(true))
1152 Out << CI->getZExtValue() << 'u';
1154 Out << CI->getSExtValue();
1160 switch (CPV->getType()->getTypeID()) {
1161 case Type::FloatTyID:
1162 case Type::DoubleTyID:
1163 case Type::X86_FP80TyID:
1164 case Type::PPC_FP128TyID:
1165 case Type::FP128TyID: {
1166 ConstantFP *FPC = cast<ConstantFP>(CPV);
1167 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1168 if (I != FPConstantMap.end()) {
1169 // Because of FP precision problems we must load from a stack allocated
1170 // value that holds the value in hex.
1171 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1173 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1176 << "*)&FPConstant" << I->second << ')';
1179 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1180 V = FPC->getValueAPF().convertToFloat();
1181 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1182 V = FPC->getValueAPF().convertToDouble();
1184 // Long double. Convert the number to double, discarding precision.
1185 // This is not awesome, but it at least makes the CBE output somewhat
1187 APFloat Tmp = FPC->getValueAPF();
1189 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1190 V = Tmp.convertToDouble();
1196 // FIXME the actual NaN bits should be emitted.
1197 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1199 const unsigned long QuietNaN = 0x7ff8UL;
1200 //const unsigned long SignalNaN = 0x7ff4UL;
1202 // We need to grab the first part of the FP #
1205 uint64_t ll = DoubleToBits(V);
1206 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1208 std::string Num(&Buffer[0], &Buffer[6]);
1209 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1211 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1212 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1213 << Buffer << "\") /*nan*/ ";
1215 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1216 << Buffer << "\") /*nan*/ ";
1217 } else if (IsInf(V)) {
1219 if (V < 0) Out << '-';
1220 Out << "LLVM_INF" <<
1221 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1225 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1226 // Print out the constant as a floating point number.
1228 sprintf(Buffer, "%a", V);
1231 Num = ftostr(FPC->getValueAPF());
1239 case Type::ArrayTyID:
1240 // Use C99 compound expression literal initializer syntax.
1243 printType(Out, CPV->getType());
1246 Out << "{ "; // Arrays are wrapped in struct types.
1247 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1248 printConstantArray(CA, Static);
1250 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1251 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1253 if (AT->getNumElements()) {
1255 Constant *CZ = Constant::getNullValue(AT->getElementType());
1256 printConstant(CZ, Static);
1257 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1259 printConstant(CZ, Static);
1264 Out << " }"; // Arrays are wrapped in struct types.
1267 case Type::VectorTyID:
1268 // Use C99 compound expression literal initializer syntax.
1271 printType(Out, CPV->getType());
1274 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1275 printConstantVector(CV, Static);
1277 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1278 const VectorType *VT = cast<VectorType>(CPV->getType());
1280 Constant *CZ = Constant::getNullValue(VT->getElementType());
1281 printConstant(CZ, Static);
1282 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1284 printConstant(CZ, Static);
1290 case Type::StructTyID:
1291 // Use C99 compound expression literal initializer syntax.
1294 printType(Out, CPV->getType());
1297 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1298 const StructType *ST = cast<StructType>(CPV->getType());
1300 if (ST->getNumElements()) {
1302 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1303 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1305 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1311 if (CPV->getNumOperands()) {
1313 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1314 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1316 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1323 case Type::PointerTyID:
1324 if (isa<ConstantPointerNull>(CPV)) {
1326 printType(Out, CPV->getType()); // sign doesn't matter
1327 Out << ")/*NULL*/0)";
1329 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1330 writeOperand(GV, Static);
1336 errs() << "Unknown constant type: " << *CPV << "\n";
1338 llvm_unreachable(0);
1342 // Some constant expressions need to be casted back to the original types
1343 // because their operands were casted to the expected type. This function takes
1344 // care of detecting that case and printing the cast for the ConstantExpr.
1345 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1346 bool NeedsExplicitCast = false;
1347 const Type *Ty = CE->getOperand(0)->getType();
1348 bool TypeIsSigned = false;
1349 switch (CE->getOpcode()) {
1350 case Instruction::Add:
1351 case Instruction::Sub:
1352 case Instruction::Mul:
1353 // We need to cast integer arithmetic so that it is always performed
1354 // as unsigned, to avoid undefined behavior on overflow.
1355 case Instruction::LShr:
1356 case Instruction::URem:
1357 case Instruction::UDiv: NeedsExplicitCast = true; break;
1358 case Instruction::AShr:
1359 case Instruction::SRem:
1360 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1361 case Instruction::SExt:
1363 NeedsExplicitCast = true;
1364 TypeIsSigned = true;
1366 case Instruction::ZExt:
1367 case Instruction::Trunc:
1368 case Instruction::FPTrunc:
1369 case Instruction::FPExt:
1370 case Instruction::UIToFP:
1371 case Instruction::SIToFP:
1372 case Instruction::FPToUI:
1373 case Instruction::FPToSI:
1374 case Instruction::PtrToInt:
1375 case Instruction::IntToPtr:
1376 case Instruction::BitCast:
1378 NeedsExplicitCast = true;
1382 if (NeedsExplicitCast) {
1384 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
1385 printSimpleType(Out, Ty, TypeIsSigned);
1387 printType(Out, Ty); // not integer, sign doesn't matter
1390 return NeedsExplicitCast;
1393 // Print a constant assuming that it is the operand for a given Opcode. The
1394 // opcodes that care about sign need to cast their operands to the expected
1395 // type before the operation proceeds. This function does the casting.
1396 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1398 // Extract the operand's type, we'll need it.
1399 const Type* OpTy = CPV->getType();
1401 // Indicate whether to do the cast or not.
1402 bool shouldCast = false;
1403 bool typeIsSigned = false;
1405 // Based on the Opcode for which this Constant is being written, determine
1406 // the new type to which the operand should be casted by setting the value
1407 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1411 // for most instructions, it doesn't matter
1413 case Instruction::Add:
1414 case Instruction::Sub:
1415 case Instruction::Mul:
1416 // We need to cast integer arithmetic so that it is always performed
1417 // as unsigned, to avoid undefined behavior on overflow.
1418 case Instruction::LShr:
1419 case Instruction::UDiv:
1420 case Instruction::URem:
1423 case Instruction::AShr:
1424 case Instruction::SDiv:
1425 case Instruction::SRem:
1427 typeIsSigned = true;
1431 // Write out the casted constant if we should, otherwise just write the
1435 printSimpleType(Out, OpTy, typeIsSigned);
1437 printConstant(CPV, false);
1440 printConstant(CPV, false);
1443 std::string CWriter::GetValueName(const Value *Operand) {
1444 // Mangle globals with the standard mangler interface for LLC compatibility.
1445 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1446 SmallString<128> Str;
1447 Mang->getNameWithPrefix(Str, GV, false);
1448 return Mangle(Str.str().str());
1451 std::string Name = Operand->getName();
1453 if (Name.empty()) { // Assign unique names to local temporaries.
1454 unsigned &No = AnonValueNumbers[Operand];
1456 No = ++NextAnonValueNumber;
1457 Name = "tmp__" + utostr(No);
1460 std::string VarName;
1461 VarName.reserve(Name.capacity());
1463 for (std::string::iterator I = Name.begin(), E = Name.end();
1467 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1468 (ch >= '0' && ch <= '9') || ch == '_')) {
1470 sprintf(buffer, "_%x_", ch);
1476 return "llvm_cbe_" + VarName;
1479 /// writeInstComputationInline - Emit the computation for the specified
1480 /// instruction inline, with no destination provided.
1481 void CWriter::writeInstComputationInline(Instruction &I) {
1482 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1484 const Type *Ty = I.getType();
1485 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1486 Ty!=Type::getInt8Ty(I.getContext()) &&
1487 Ty!=Type::getInt16Ty(I.getContext()) &&
1488 Ty!=Type::getInt32Ty(I.getContext()) &&
1489 Ty!=Type::getInt64Ty(I.getContext()))) {
1490 llvm_report_error("The C backend does not currently support integer "
1491 "types of widths other than 1, 8, 16, 32, 64.\n"
1492 "This is being tracked as PR 4158.");
1495 // If this is a non-trivial bool computation, make sure to truncate down to
1496 // a 1 bit value. This is important because we want "add i1 x, y" to return
1497 // "0" when x and y are true, not "2" for example.
1498 bool NeedBoolTrunc = false;
1499 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1500 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1501 NeedBoolTrunc = true;
1513 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1514 if (Instruction *I = dyn_cast<Instruction>(Operand))
1515 // Should we inline this instruction to build a tree?
1516 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1518 writeInstComputationInline(*I);
1523 Constant* CPV = dyn_cast<Constant>(Operand);
1525 if (CPV && !isa<GlobalValue>(CPV))
1526 printConstant(CPV, Static);
1528 Out << GetValueName(Operand);
1531 void CWriter::writeOperand(Value *Operand, bool Static) {
1532 bool isAddressImplicit = isAddressExposed(Operand);
1533 if (isAddressImplicit)
1534 Out << "(&"; // Global variables are referenced as their addresses by llvm
1536 writeOperandInternal(Operand, Static);
1538 if (isAddressImplicit)
1542 // Some instructions need to have their result value casted back to the
1543 // original types because their operands were casted to the expected type.
1544 // This function takes care of detecting that case and printing the cast
1545 // for the Instruction.
1546 bool CWriter::writeInstructionCast(const Instruction &I) {
1547 const Type *Ty = I.getOperand(0)->getType();
1548 switch (I.getOpcode()) {
1549 case Instruction::Add:
1550 case Instruction::Sub:
1551 case Instruction::Mul:
1552 // We need to cast integer arithmetic so that it is always performed
1553 // as unsigned, to avoid undefined behavior on overflow.
1554 case Instruction::LShr:
1555 case Instruction::URem:
1556 case Instruction::UDiv:
1558 printSimpleType(Out, Ty, false);
1561 case Instruction::AShr:
1562 case Instruction::SRem:
1563 case Instruction::SDiv:
1565 printSimpleType(Out, Ty, true);
1573 // Write the operand with a cast to another type based on the Opcode being used.
1574 // This will be used in cases where an instruction has specific type
1575 // requirements (usually signedness) for its operands.
1576 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1578 // Extract the operand's type, we'll need it.
1579 const Type* OpTy = Operand->getType();
1581 // Indicate whether to do the cast or not.
1582 bool shouldCast = false;
1584 // Indicate whether the cast should be to a signed type or not.
1585 bool castIsSigned = false;
1587 // Based on the Opcode for which this Operand is being written, determine
1588 // the new type to which the operand should be casted by setting the value
1589 // of OpTy. If we change OpTy, also set shouldCast to true.
1592 // for most instructions, it doesn't matter
1594 case Instruction::Add:
1595 case Instruction::Sub:
1596 case Instruction::Mul:
1597 // We need to cast integer arithmetic so that it is always performed
1598 // as unsigned, to avoid undefined behavior on overflow.
1599 case Instruction::LShr:
1600 case Instruction::UDiv:
1601 case Instruction::URem: // Cast to unsigned first
1603 castIsSigned = false;
1605 case Instruction::GetElementPtr:
1606 case Instruction::AShr:
1607 case Instruction::SDiv:
1608 case Instruction::SRem: // Cast to signed first
1610 castIsSigned = true;
1614 // Write out the casted operand if we should, otherwise just write the
1618 printSimpleType(Out, OpTy, castIsSigned);
1620 writeOperand(Operand);
1623 writeOperand(Operand);
1626 // Write the operand with a cast to another type based on the icmp predicate
1628 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1629 // This has to do a cast to ensure the operand has the right signedness.
1630 // Also, if the operand is a pointer, we make sure to cast to an integer when
1631 // doing the comparison both for signedness and so that the C compiler doesn't
1632 // optimize things like "p < NULL" to false (p may contain an integer value
1634 bool shouldCast = Cmp.isRelational();
1636 // Write out the casted operand if we should, otherwise just write the
1639 writeOperand(Operand);
1643 // Should this be a signed comparison? If so, convert to signed.
1644 bool castIsSigned = Cmp.isSigned();
1646 // If the operand was a pointer, convert to a large integer type.
1647 const Type* OpTy = Operand->getType();
1648 if (isa<PointerType>(OpTy))
1649 OpTy = TD->getIntPtrType(Operand->getContext());
1652 printSimpleType(Out, OpTy, castIsSigned);
1654 writeOperand(Operand);
1658 // generateCompilerSpecificCode - This is where we add conditional compilation
1659 // directives to cater to specific compilers as need be.
1661 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1662 const TargetData *TD) {
1663 // Alloca is hard to get, and we don't want to include stdlib.h here.
1664 Out << "/* get a declaration for alloca */\n"
1665 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1666 << "#define alloca(x) __builtin_alloca((x))\n"
1667 << "#define _alloca(x) __builtin_alloca((x))\n"
1668 << "#elif defined(__APPLE__)\n"
1669 << "extern void *__builtin_alloca(unsigned long);\n"
1670 << "#define alloca(x) __builtin_alloca(x)\n"
1671 << "#define longjmp _longjmp\n"
1672 << "#define setjmp _setjmp\n"
1673 << "#elif defined(__sun__)\n"
1674 << "#if defined(__sparcv9)\n"
1675 << "extern void *__builtin_alloca(unsigned long);\n"
1677 << "extern void *__builtin_alloca(unsigned int);\n"
1679 << "#define alloca(x) __builtin_alloca(x)\n"
1680 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1681 << "#define alloca(x) __builtin_alloca(x)\n"
1682 << "#elif defined(_MSC_VER)\n"
1683 << "#define inline _inline\n"
1684 << "#define alloca(x) _alloca(x)\n"
1686 << "#include <alloca.h>\n"
1689 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1690 // If we aren't being compiled with GCC, just drop these attributes.
1691 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1692 << "#define __attribute__(X)\n"
1695 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1696 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1697 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1698 << "#elif defined(__GNUC__)\n"
1699 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1701 << "#define __EXTERNAL_WEAK__\n"
1704 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1705 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1706 << "#define __ATTRIBUTE_WEAK__\n"
1707 << "#elif defined(__GNUC__)\n"
1708 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1710 << "#define __ATTRIBUTE_WEAK__\n"
1713 // Add hidden visibility support. FIXME: APPLE_CC?
1714 Out << "#if defined(__GNUC__)\n"
1715 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1718 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1719 // From the GCC documentation:
1721 // double __builtin_nan (const char *str)
1723 // This is an implementation of the ISO C99 function nan.
1725 // Since ISO C99 defines this function in terms of strtod, which we do
1726 // not implement, a description of the parsing is in order. The string is
1727 // parsed as by strtol; that is, the base is recognized by leading 0 or
1728 // 0x prefixes. The number parsed is placed in the significand such that
1729 // the least significant bit of the number is at the least significant
1730 // bit of the significand. The number is truncated to fit the significand
1731 // field provided. The significand is forced to be a quiet NaN.
1733 // This function, if given a string literal, is evaluated early enough
1734 // that it is considered a compile-time constant.
1736 // float __builtin_nanf (const char *str)
1738 // Similar to __builtin_nan, except the return type is float.
1740 // double __builtin_inf (void)
1742 // Similar to __builtin_huge_val, except a warning is generated if the
1743 // target floating-point format does not support infinities. This
1744 // function is suitable for implementing the ISO C99 macro INFINITY.
1746 // float __builtin_inff (void)
1748 // Similar to __builtin_inf, except the return type is float.
1749 Out << "#ifdef __GNUC__\n"
1750 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1751 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1752 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1753 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1754 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1755 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1756 << "#define LLVM_PREFETCH(addr,rw,locality) "
1757 "__builtin_prefetch(addr,rw,locality)\n"
1758 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1759 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1760 << "#define LLVM_ASM __asm__\n"
1762 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1763 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1764 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1765 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1766 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1767 << "#define LLVM_INFF 0.0F /* Float */\n"
1768 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1769 << "#define __ATTRIBUTE_CTOR__\n"
1770 << "#define __ATTRIBUTE_DTOR__\n"
1771 << "#define LLVM_ASM(X)\n"
1774 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1775 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1776 << "#define __builtin_stack_restore(X) /* noop */\n"
1779 // Output typedefs for 128-bit integers. If these are needed with a
1780 // 32-bit target or with a C compiler that doesn't support mode(TI),
1781 // more drastic measures will be needed.
1782 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1783 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1784 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1787 // Output target-specific code that should be inserted into main.
1788 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1791 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1792 /// the StaticTors set.
1793 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1794 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1795 if (!InitList) return;
1797 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1798 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1799 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1801 if (CS->getOperand(1)->isNullValue())
1802 return; // Found a null terminator, exit printing.
1803 Constant *FP = CS->getOperand(1);
1804 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1806 FP = CE->getOperand(0);
1807 if (Function *F = dyn_cast<Function>(FP))
1808 StaticTors.insert(F);
1812 enum SpecialGlobalClass {
1814 GlobalCtors, GlobalDtors,
1818 /// getGlobalVariableClass - If this is a global that is specially recognized
1819 /// by LLVM, return a code that indicates how we should handle it.
1820 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1821 // If this is a global ctors/dtors list, handle it now.
1822 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1823 if (GV->getName() == "llvm.global_ctors")
1825 else if (GV->getName() == "llvm.global_dtors")
1829 // Otherwise, it it is other metadata, don't print it. This catches things
1830 // like debug information.
1831 if (GV->getSection() == "llvm.metadata")
1837 // PrintEscapedString - Print each character of the specified string, escaping
1838 // it if it is not printable or if it is an escape char.
1839 static void PrintEscapedString(const char *Str, unsigned Length,
1841 for (unsigned i = 0; i != Length; ++i) {
1842 unsigned char C = Str[i];
1843 if (isprint(C) && C != '\\' && C != '"')
1852 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1856 // PrintEscapedString - Print each character of the specified string, escaping
1857 // it if it is not printable or if it is an escape char.
1858 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1859 PrintEscapedString(Str.c_str(), Str.size(), Out);
1862 bool CWriter::doInitialization(Module &M) {
1863 FunctionPass::doInitialization(M);
1868 TD = new TargetData(&M);
1869 IL = new IntrinsicLowering(*TD);
1870 IL->AddPrototypes(M);
1872 // Ensure that all structure types have names...
1873 Mang = new Mangler(M);
1875 // Keep track of which functions are static ctors/dtors so they can have
1876 // an attribute added to their prototypes.
1877 std::set<Function*> StaticCtors, StaticDtors;
1878 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1880 switch (getGlobalVariableClass(I)) {
1883 FindStaticTors(I, StaticCtors);
1886 FindStaticTors(I, StaticDtors);
1891 // get declaration for alloca
1892 Out << "/* Provide Declarations */\n";
1893 Out << "#include <stdarg.h>\n"; // Varargs support
1894 Out << "#include <setjmp.h>\n"; // Unwind support
1895 generateCompilerSpecificCode(Out, TD);
1897 // Provide a definition for `bool' if not compiling with a C++ compiler.
1899 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1901 << "\n\n/* Support for floating point constants */\n"
1902 << "typedef unsigned long long ConstantDoubleTy;\n"
1903 << "typedef unsigned int ConstantFloatTy;\n"
1904 << "typedef struct { unsigned long long f1; unsigned short f2; "
1905 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1906 // This is used for both kinds of 128-bit long double; meaning differs.
1907 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1908 " ConstantFP128Ty;\n"
1909 << "\n\n/* Global Declarations */\n";
1911 // First output all the declarations for the program, because C requires
1912 // Functions & globals to be declared before they are used.
1914 if (!M.getModuleInlineAsm().empty()) {
1915 Out << "/* Module asm statements */\n"
1918 // Split the string into lines, to make it easier to read the .ll file.
1919 std::string Asm = M.getModuleInlineAsm();
1921 size_t NewLine = Asm.find_first_of('\n', CurPos);
1922 while (NewLine != std::string::npos) {
1923 // We found a newline, print the portion of the asm string from the
1924 // last newline up to this newline.
1926 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1930 NewLine = Asm.find_first_of('\n', CurPos);
1933 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1935 << "/* End Module asm statements */\n";
1938 // Loop over the symbol table, emitting all named constants...
1939 printModuleTypes(M.getTypeSymbolTable());
1941 // Global variable declarations...
1942 if (!M.global_empty()) {
1943 Out << "\n/* External Global Variable Declarations */\n";
1944 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1947 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1948 I->hasCommonLinkage())
1950 else if (I->hasDLLImportLinkage())
1951 Out << "__declspec(dllimport) ";
1953 continue; // Internal Global
1955 // Thread Local Storage
1956 if (I->isThreadLocal())
1959 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1961 if (I->hasExternalWeakLinkage())
1962 Out << " __EXTERNAL_WEAK__";
1967 // Function declarations
1968 Out << "\n/* Function Declarations */\n";
1969 Out << "double fmod(double, double);\n"; // Support for FP rem
1970 Out << "float fmodf(float, float);\n";
1971 Out << "long double fmodl(long double, long double);\n";
1973 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1974 // Don't print declarations for intrinsic functions.
1975 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1976 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1977 if (I->hasExternalWeakLinkage())
1979 printFunctionSignature(I, true);
1980 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1981 Out << " __ATTRIBUTE_WEAK__";
1982 if (I->hasExternalWeakLinkage())
1983 Out << " __EXTERNAL_WEAK__";
1984 if (StaticCtors.count(I))
1985 Out << " __ATTRIBUTE_CTOR__";
1986 if (StaticDtors.count(I))
1987 Out << " __ATTRIBUTE_DTOR__";
1988 if (I->hasHiddenVisibility())
1989 Out << " __HIDDEN__";
1991 if (I->hasName() && I->getName()[0] == 1)
1992 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
1998 // Output the global variable declarations
1999 if (!M.global_empty()) {
2000 Out << "\n\n/* Global Variable Declarations */\n";
2001 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2003 if (!I->isDeclaration()) {
2004 // Ignore special globals, such as debug info.
2005 if (getGlobalVariableClass(I))
2008 if (I->hasLocalLinkage())
2013 // Thread Local Storage
2014 if (I->isThreadLocal())
2017 printType(Out, I->getType()->getElementType(), false,
2020 if (I->hasLinkOnceLinkage())
2021 Out << " __attribute__((common))";
2022 else if (I->hasCommonLinkage()) // FIXME is this right?
2023 Out << " __ATTRIBUTE_WEAK__";
2024 else if (I->hasWeakLinkage())
2025 Out << " __ATTRIBUTE_WEAK__";
2026 else if (I->hasExternalWeakLinkage())
2027 Out << " __EXTERNAL_WEAK__";
2028 if (I->hasHiddenVisibility())
2029 Out << " __HIDDEN__";
2034 // Output the global variable definitions and contents...
2035 if (!M.global_empty()) {
2036 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
2037 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2039 if (!I->isDeclaration()) {
2040 // Ignore special globals, such as debug info.
2041 if (getGlobalVariableClass(I))
2044 if (I->hasLocalLinkage())
2046 else if (I->hasDLLImportLinkage())
2047 Out << "__declspec(dllimport) ";
2048 else if (I->hasDLLExportLinkage())
2049 Out << "__declspec(dllexport) ";
2051 // Thread Local Storage
2052 if (I->isThreadLocal())
2055 printType(Out, I->getType()->getElementType(), false,
2057 if (I->hasLinkOnceLinkage())
2058 Out << " __attribute__((common))";
2059 else if (I->hasWeakLinkage())
2060 Out << " __ATTRIBUTE_WEAK__";
2061 else if (I->hasCommonLinkage())
2062 Out << " __ATTRIBUTE_WEAK__";
2064 if (I->hasHiddenVisibility())
2065 Out << " __HIDDEN__";
2067 // If the initializer is not null, emit the initializer. If it is null,
2068 // we try to avoid emitting large amounts of zeros. The problem with
2069 // this, however, occurs when the variable has weak linkage. In this
2070 // case, the assembler will complain about the variable being both weak
2071 // and common, so we disable this optimization.
2072 // FIXME common linkage should avoid this problem.
2073 if (!I->getInitializer()->isNullValue()) {
2075 writeOperand(I->getInitializer(), true);
2076 } else if (I->hasWeakLinkage()) {
2077 // We have to specify an initializer, but it doesn't have to be
2078 // complete. If the value is an aggregate, print out { 0 }, and let
2079 // the compiler figure out the rest of the zeros.
2081 if (isa<StructType>(I->getInitializer()->getType()) ||
2082 isa<VectorType>(I->getInitializer()->getType())) {
2084 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2085 // As with structs and vectors, but with an extra set of braces
2086 // because arrays are wrapped in structs.
2089 // Just print it out normally.
2090 writeOperand(I->getInitializer(), true);
2098 Out << "\n\n/* Function Bodies */\n";
2100 // Emit some helper functions for dealing with FCMP instruction's
2102 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2103 Out << "return X == X && Y == Y; }\n";
2104 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2105 Out << "return X != X || Y != Y; }\n";
2106 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2107 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2108 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2109 Out << "return X != Y; }\n";
2110 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2111 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2112 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2113 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2114 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2115 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2116 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2117 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2118 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2119 Out << "return X == Y ; }\n";
2120 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2121 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2122 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2123 Out << "return X < Y ; }\n";
2124 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2125 Out << "return X > Y ; }\n";
2126 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2127 Out << "return X <= Y ; }\n";
2128 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2129 Out << "return X >= Y ; }\n";
2134 /// Output all floating point constants that cannot be printed accurately...
2135 void CWriter::printFloatingPointConstants(Function &F) {
2136 // Scan the module for floating point constants. If any FP constant is used
2137 // in the function, we want to redirect it here so that we do not depend on
2138 // the precision of the printed form, unless the printed form preserves
2141 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2143 printFloatingPointConstants(*I);
2148 void CWriter::printFloatingPointConstants(const Constant *C) {
2149 // If this is a constant expression, recursively check for constant fp values.
2150 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2151 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2152 printFloatingPointConstants(CE->getOperand(i));
2156 // Otherwise, check for a FP constant that we need to print.
2157 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2159 // Do not put in FPConstantMap if safe.
2160 isFPCSafeToPrint(FPC) ||
2161 // Already printed this constant?
2162 FPConstantMap.count(FPC))
2165 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2167 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2168 double Val = FPC->getValueAPF().convertToDouble();
2169 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2170 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2171 << " = 0x" << utohexstr(i)
2172 << "ULL; /* " << Val << " */\n";
2173 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2174 float Val = FPC->getValueAPF().convertToFloat();
2175 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2177 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2178 << " = 0x" << utohexstr(i)
2179 << "U; /* " << Val << " */\n";
2180 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2181 // api needed to prevent premature destruction
2182 APInt api = FPC->getValueAPF().bitcastToAPInt();
2183 const uint64_t *p = api.getRawData();
2184 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2185 << " = { 0x" << utohexstr(p[0])
2186 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2187 << "}; /* Long double constant */\n";
2188 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2189 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2190 APInt api = FPC->getValueAPF().bitcastToAPInt();
2191 const uint64_t *p = api.getRawData();
2192 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2194 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2195 << "}; /* Long double constant */\n";
2198 llvm_unreachable("Unknown float type!");
2204 /// printSymbolTable - Run through symbol table looking for type names. If a
2205 /// type name is found, emit its declaration...
2207 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2208 Out << "/* Helper union for bitcasts */\n";
2209 Out << "typedef union {\n";
2210 Out << " unsigned int Int32;\n";
2211 Out << " unsigned long long Int64;\n";
2212 Out << " float Float;\n";
2213 Out << " double Double;\n";
2214 Out << "} llvmBitCastUnion;\n";
2216 // We are only interested in the type plane of the symbol table.
2217 TypeSymbolTable::const_iterator I = TST.begin();
2218 TypeSymbolTable::const_iterator End = TST.end();
2220 // If there are no type names, exit early.
2221 if (I == End) return;
2223 // Print out forward declarations for structure types before anything else!
2224 Out << "/* Structure forward decls */\n";
2225 for (; I != End; ++I) {
2226 std::string Name = "struct " + Mangle("l_"+I->first);
2227 Out << Name << ";\n";
2228 TypeNames.insert(std::make_pair(I->second, Name));
2233 // Now we can print out typedefs. Above, we guaranteed that this can only be
2234 // for struct or opaque types.
2235 Out << "/* Typedefs */\n";
2236 for (I = TST.begin(); I != End; ++I) {
2237 std::string Name = Mangle("l_"+I->first);
2239 printType(Out, I->second, false, Name);
2245 // Keep track of which structures have been printed so far...
2246 std::set<const Type *> StructPrinted;
2248 // Loop over all structures then push them into the stack so they are
2249 // printed in the correct order.
2251 Out << "/* Structure contents */\n";
2252 for (I = TST.begin(); I != End; ++I)
2253 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2254 // Only print out used types!
2255 printContainedStructs(I->second, StructPrinted);
2258 // Push the struct onto the stack and recursively push all structs
2259 // this one depends on.
2261 // TODO: Make this work properly with vector types
2263 void CWriter::printContainedStructs(const Type *Ty,
2264 std::set<const Type*> &StructPrinted) {
2265 // Don't walk through pointers.
2266 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2268 // Print all contained types first.
2269 for (Type::subtype_iterator I = Ty->subtype_begin(),
2270 E = Ty->subtype_end(); I != E; ++I)
2271 printContainedStructs(*I, StructPrinted);
2273 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2274 // Check to see if we have already printed this struct.
2275 if (StructPrinted.insert(Ty).second) {
2276 // Print structure type out.
2277 std::string Name = TypeNames[Ty];
2278 printType(Out, Ty, false, Name, true);
2284 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2285 /// isStructReturn - Should this function actually return a struct by-value?
2286 bool isStructReturn = F->hasStructRetAttr();
2288 if (F->hasLocalLinkage()) Out << "static ";
2289 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2290 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2291 switch (F->getCallingConv()) {
2292 case CallingConv::X86_StdCall:
2293 Out << "__attribute__((stdcall)) ";
2295 case CallingConv::X86_FastCall:
2296 Out << "__attribute__((fastcall)) ";
2302 // Loop over the arguments, printing them...
2303 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2304 const AttrListPtr &PAL = F->getAttributes();
2306 std::stringstream FunctionInnards;
2308 // Print out the name...
2309 FunctionInnards << GetValueName(F) << '(';
2311 bool PrintedArg = false;
2312 if (!F->isDeclaration()) {
2313 if (!F->arg_empty()) {
2314 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2317 // If this is a struct-return function, don't print the hidden
2318 // struct-return argument.
2319 if (isStructReturn) {
2320 assert(I != E && "Invalid struct return function!");
2325 std::string ArgName;
2326 for (; I != E; ++I) {
2327 if (PrintedArg) FunctionInnards << ", ";
2328 if (I->hasName() || !Prototype)
2329 ArgName = GetValueName(I);
2332 const Type *ArgTy = I->getType();
2333 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2334 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2335 ByValParams.insert(I);
2337 printType(FunctionInnards, ArgTy,
2338 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2345 // Loop over the arguments, printing them.
2346 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2349 // If this is a struct-return function, don't print the hidden
2350 // struct-return argument.
2351 if (isStructReturn) {
2352 assert(I != E && "Invalid struct return function!");
2357 for (; I != E; ++I) {
2358 if (PrintedArg) FunctionInnards << ", ";
2359 const Type *ArgTy = *I;
2360 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2361 assert(isa<PointerType>(ArgTy));
2362 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2364 printType(FunctionInnards, ArgTy,
2365 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2371 // Finish printing arguments... if this is a vararg function, print the ...,
2372 // unless there are no known types, in which case, we just emit ().
2374 if (FT->isVarArg() && PrintedArg) {
2375 if (PrintedArg) FunctionInnards << ", ";
2376 FunctionInnards << "..."; // Output varargs portion of signature!
2377 } else if (!FT->isVarArg() && !PrintedArg) {
2378 FunctionInnards << "void"; // ret() -> ret(void) in C.
2380 FunctionInnards << ')';
2382 // Get the return tpe for the function.
2384 if (!isStructReturn)
2385 RetTy = F->getReturnType();
2387 // If this is a struct-return function, print the struct-return type.
2388 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2391 // Print out the return type and the signature built above.
2392 printType(Out, RetTy,
2393 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2394 FunctionInnards.str());
2397 static inline bool isFPIntBitCast(const Instruction &I) {
2398 if (!isa<BitCastInst>(I))
2400 const Type *SrcTy = I.getOperand(0)->getType();
2401 const Type *DstTy = I.getType();
2402 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2403 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2406 void CWriter::printFunction(Function &F) {
2407 /// isStructReturn - Should this function actually return a struct by-value?
2408 bool isStructReturn = F.hasStructRetAttr();
2410 printFunctionSignature(&F, false);
2413 // If this is a struct return function, handle the result with magic.
2414 if (isStructReturn) {
2415 const Type *StructTy =
2416 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2418 printType(Out, StructTy, false, "StructReturn");
2419 Out << "; /* Struct return temporary */\n";
2422 printType(Out, F.arg_begin()->getType(), false,
2423 GetValueName(F.arg_begin()));
2424 Out << " = &StructReturn;\n";
2427 bool PrintedVar = false;
2429 // print local variable information for the function
2430 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2431 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2433 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2434 Out << "; /* Address-exposed local */\n";
2436 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2437 !isInlinableInst(*I)) {
2439 printType(Out, I->getType(), false, GetValueName(&*I));
2442 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2444 printType(Out, I->getType(), false,
2445 GetValueName(&*I)+"__PHI_TEMPORARY");
2450 // We need a temporary for the BitCast to use so it can pluck a value out
2451 // of a union to do the BitCast. This is separate from the need for a
2452 // variable to hold the result of the BitCast.
2453 if (isFPIntBitCast(*I)) {
2454 Out << " llvmBitCastUnion " << GetValueName(&*I)
2455 << "__BITCAST_TEMPORARY;\n";
2463 if (F.hasExternalLinkage() && F.getName() == "main")
2464 Out << " CODE_FOR_MAIN();\n";
2466 // print the basic blocks
2467 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2468 if (Loop *L = LI->getLoopFor(BB)) {
2469 if (L->getHeader() == BB && L->getParentLoop() == 0)
2472 printBasicBlock(BB);
2479 void CWriter::printLoop(Loop *L) {
2480 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2481 << "' to make GCC happy */\n";
2482 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2483 BasicBlock *BB = L->getBlocks()[i];
2484 Loop *BBLoop = LI->getLoopFor(BB);
2486 printBasicBlock(BB);
2487 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2490 Out << " } while (1); /* end of syntactic loop '"
2491 << L->getHeader()->getName() << "' */\n";
2494 void CWriter::printBasicBlock(BasicBlock *BB) {
2496 // Don't print the label for the basic block if there are no uses, or if
2497 // the only terminator use is the predecessor basic block's terminator.
2498 // We have to scan the use list because PHI nodes use basic blocks too but
2499 // do not require a label to be generated.
2501 bool NeedsLabel = false;
2502 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2503 if (isGotoCodeNecessary(*PI, BB)) {
2508 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2510 // Output all of the instructions in the basic block...
2511 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2513 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2514 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2519 writeInstComputationInline(*II);
2524 // Don't emit prefix or suffix for the terminator.
2525 visit(*BB->getTerminator());
2529 // Specific Instruction type classes... note that all of the casts are
2530 // necessary because we use the instruction classes as opaque types...
2532 void CWriter::visitReturnInst(ReturnInst &I) {
2533 // If this is a struct return function, return the temporary struct.
2534 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2536 if (isStructReturn) {
2537 Out << " return StructReturn;\n";
2541 // Don't output a void return if this is the last basic block in the function
2542 if (I.getNumOperands() == 0 &&
2543 &*--I.getParent()->getParent()->end() == I.getParent() &&
2544 !I.getParent()->size() == 1) {
2548 if (I.getNumOperands() > 1) {
2551 printType(Out, I.getParent()->getParent()->getReturnType());
2552 Out << " llvm_cbe_mrv_temp = {\n";
2553 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2555 writeOperand(I.getOperand(i));
2561 Out << " return llvm_cbe_mrv_temp;\n";
2567 if (I.getNumOperands()) {
2569 writeOperand(I.getOperand(0));
2574 void CWriter::visitSwitchInst(SwitchInst &SI) {
2577 writeOperand(SI.getOperand(0));
2578 Out << ") {\n default:\n";
2579 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2580 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2582 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2584 writeOperand(SI.getOperand(i));
2586 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2587 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2588 printBranchToBlock(SI.getParent(), Succ, 2);
2589 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2595 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2596 Out << " goto *(void*)(";
2597 writeOperand(IBI.getOperand(0));
2601 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2602 Out << " /*UNREACHABLE*/;\n";
2605 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2606 /// FIXME: This should be reenabled, but loop reordering safe!!
2609 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2610 return true; // Not the direct successor, we need a goto.
2612 //isa<SwitchInst>(From->getTerminator())
2614 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2619 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2620 BasicBlock *Successor,
2622 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2623 PHINode *PN = cast<PHINode>(I);
2624 // Now we have to do the printing.
2625 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2626 if (!isa<UndefValue>(IV)) {
2627 Out << std::string(Indent, ' ');
2628 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2630 Out << "; /* for PHI node */\n";
2635 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2637 if (isGotoCodeNecessary(CurBB, Succ)) {
2638 Out << std::string(Indent, ' ') << " goto ";
2644 // Branch instruction printing - Avoid printing out a branch to a basic block
2645 // that immediately succeeds the current one.
2647 void CWriter::visitBranchInst(BranchInst &I) {
2649 if (I.isConditional()) {
2650 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2652 writeOperand(I.getCondition());
2655 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2656 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2658 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2659 Out << " } else {\n";
2660 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2661 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2664 // First goto not necessary, assume second one is...
2666 writeOperand(I.getCondition());
2669 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2670 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2675 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2676 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2681 // PHI nodes get copied into temporary values at the end of predecessor basic
2682 // blocks. We now need to copy these temporary values into the REAL value for
2684 void CWriter::visitPHINode(PHINode &I) {
2686 Out << "__PHI_TEMPORARY";
2690 void CWriter::visitBinaryOperator(Instruction &I) {
2691 // binary instructions, shift instructions, setCond instructions.
2692 assert(!isa<PointerType>(I.getType()));
2694 // We must cast the results of binary operations which might be promoted.
2695 bool needsCast = false;
2696 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2697 (I.getType() == Type::getInt16Ty(I.getContext()))
2698 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2701 printType(Out, I.getType(), false);
2705 // If this is a negation operation, print it out as such. For FP, we don't
2706 // want to print "-0.0 - X".
2707 if (BinaryOperator::isNeg(&I)) {
2709 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2711 } else if (BinaryOperator::isFNeg(&I)) {
2713 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2715 } else if (I.getOpcode() == Instruction::FRem) {
2716 // Output a call to fmod/fmodf instead of emitting a%b
2717 if (I.getType() == Type::getFloatTy(I.getContext()))
2719 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2721 else // all 3 flavors of long double
2723 writeOperand(I.getOperand(0));
2725 writeOperand(I.getOperand(1));
2729 // Write out the cast of the instruction's value back to the proper type
2731 bool NeedsClosingParens = writeInstructionCast(I);
2733 // Certain instructions require the operand to be forced to a specific type
2734 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2735 // below for operand 1
2736 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2738 switch (I.getOpcode()) {
2739 case Instruction::Add:
2740 case Instruction::FAdd: Out << " + "; break;
2741 case Instruction::Sub:
2742 case Instruction::FSub: Out << " - "; break;
2743 case Instruction::Mul:
2744 case Instruction::FMul: Out << " * "; break;
2745 case Instruction::URem:
2746 case Instruction::SRem:
2747 case Instruction::FRem: Out << " % "; break;
2748 case Instruction::UDiv:
2749 case Instruction::SDiv:
2750 case Instruction::FDiv: Out << " / "; break;
2751 case Instruction::And: Out << " & "; break;
2752 case Instruction::Or: Out << " | "; break;
2753 case Instruction::Xor: Out << " ^ "; break;
2754 case Instruction::Shl : Out << " << "; break;
2755 case Instruction::LShr:
2756 case Instruction::AShr: Out << " >> "; break;
2759 errs() << "Invalid operator type!" << I;
2761 llvm_unreachable(0);
2764 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2765 if (NeedsClosingParens)
2774 void CWriter::visitICmpInst(ICmpInst &I) {
2775 // We must cast the results of icmp which might be promoted.
2776 bool needsCast = false;
2778 // Write out the cast of the instruction's value back to the proper type
2780 bool NeedsClosingParens = writeInstructionCast(I);
2782 // Certain icmp predicate require the operand to be forced to a specific type
2783 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2784 // below for operand 1
2785 writeOperandWithCast(I.getOperand(0), I);
2787 switch (I.getPredicate()) {
2788 case ICmpInst::ICMP_EQ: Out << " == "; break;
2789 case ICmpInst::ICMP_NE: Out << " != "; break;
2790 case ICmpInst::ICMP_ULE:
2791 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2792 case ICmpInst::ICMP_UGE:
2793 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2794 case ICmpInst::ICMP_ULT:
2795 case ICmpInst::ICMP_SLT: Out << " < "; break;
2796 case ICmpInst::ICMP_UGT:
2797 case ICmpInst::ICMP_SGT: Out << " > "; break;
2800 errs() << "Invalid icmp predicate!" << I;
2802 llvm_unreachable(0);
2805 writeOperandWithCast(I.getOperand(1), I);
2806 if (NeedsClosingParens)
2814 void CWriter::visitFCmpInst(FCmpInst &I) {
2815 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2819 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2825 switch (I.getPredicate()) {
2826 default: llvm_unreachable("Illegal FCmp predicate");
2827 case FCmpInst::FCMP_ORD: op = "ord"; break;
2828 case FCmpInst::FCMP_UNO: op = "uno"; break;
2829 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2830 case FCmpInst::FCMP_UNE: op = "une"; break;
2831 case FCmpInst::FCMP_ULT: op = "ult"; break;
2832 case FCmpInst::FCMP_ULE: op = "ule"; break;
2833 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2834 case FCmpInst::FCMP_UGE: op = "uge"; break;
2835 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2836 case FCmpInst::FCMP_ONE: op = "one"; break;
2837 case FCmpInst::FCMP_OLT: op = "olt"; break;
2838 case FCmpInst::FCMP_OLE: op = "ole"; break;
2839 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2840 case FCmpInst::FCMP_OGE: op = "oge"; break;
2843 Out << "llvm_fcmp_" << op << "(";
2844 // Write the first operand
2845 writeOperand(I.getOperand(0));
2847 // Write the second operand
2848 writeOperand(I.getOperand(1));
2852 static const char * getFloatBitCastField(const Type *Ty) {
2853 switch (Ty->getTypeID()) {
2854 default: llvm_unreachable("Invalid Type");
2855 case Type::FloatTyID: return "Float";
2856 case Type::DoubleTyID: return "Double";
2857 case Type::IntegerTyID: {
2858 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2867 void CWriter::visitCastInst(CastInst &I) {
2868 const Type *DstTy = I.getType();
2869 const Type *SrcTy = I.getOperand(0)->getType();
2870 if (isFPIntBitCast(I)) {
2872 // These int<->float and long<->double casts need to be handled specially
2873 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2874 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2875 writeOperand(I.getOperand(0));
2876 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2877 << getFloatBitCastField(I.getType());
2883 printCast(I.getOpcode(), SrcTy, DstTy);
2885 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2886 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2887 I.getOpcode() == Instruction::SExt)
2890 writeOperand(I.getOperand(0));
2892 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2893 (I.getOpcode() == Instruction::Trunc ||
2894 I.getOpcode() == Instruction::FPToUI ||
2895 I.getOpcode() == Instruction::FPToSI ||
2896 I.getOpcode() == Instruction::PtrToInt)) {
2897 // Make sure we really get a trunc to bool by anding the operand with 1
2903 void CWriter::visitSelectInst(SelectInst &I) {
2905 writeOperand(I.getCondition());
2907 writeOperand(I.getTrueValue());
2909 writeOperand(I.getFalseValue());
2914 void CWriter::lowerIntrinsics(Function &F) {
2915 // This is used to keep track of intrinsics that get generated to a lowered
2916 // function. We must generate the prototypes before the function body which
2917 // will only be expanded on first use (by the loop below).
2918 std::vector<Function*> prototypesToGen;
2920 // Examine all the instructions in this function to find the intrinsics that
2921 // need to be lowered.
2922 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2923 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2924 if (CallInst *CI = dyn_cast<CallInst>(I++))
2925 if (Function *F = CI->getCalledFunction())
2926 switch (F->getIntrinsicID()) {
2927 case Intrinsic::not_intrinsic:
2928 case Intrinsic::memory_barrier:
2929 case Intrinsic::vastart:
2930 case Intrinsic::vacopy:
2931 case Intrinsic::vaend:
2932 case Intrinsic::returnaddress:
2933 case Intrinsic::frameaddress:
2934 case Intrinsic::setjmp:
2935 case Intrinsic::longjmp:
2936 case Intrinsic::prefetch:
2937 case Intrinsic::powi:
2938 case Intrinsic::x86_sse_cmp_ss:
2939 case Intrinsic::x86_sse_cmp_ps:
2940 case Intrinsic::x86_sse2_cmp_sd:
2941 case Intrinsic::x86_sse2_cmp_pd:
2942 case Intrinsic::ppc_altivec_lvsl:
2943 // We directly implement these intrinsics
2946 // If this is an intrinsic that directly corresponds to a GCC
2947 // builtin, we handle it.
2948 const char *BuiltinName = "";
2949 #define GET_GCC_BUILTIN_NAME
2950 #include "llvm/Intrinsics.gen"
2951 #undef GET_GCC_BUILTIN_NAME
2952 // If we handle it, don't lower it.
2953 if (BuiltinName[0]) break;
2955 // All other intrinsic calls we must lower.
2956 Instruction *Before = 0;
2957 if (CI != &BB->front())
2958 Before = prior(BasicBlock::iterator(CI));
2960 IL->LowerIntrinsicCall(CI);
2961 if (Before) { // Move iterator to instruction after call
2966 // If the intrinsic got lowered to another call, and that call has
2967 // a definition then we need to make sure its prototype is emitted
2968 // before any calls to it.
2969 if (CallInst *Call = dyn_cast<CallInst>(I))
2970 if (Function *NewF = Call->getCalledFunction())
2971 if (!NewF->isDeclaration())
2972 prototypesToGen.push_back(NewF);
2977 // We may have collected some prototypes to emit in the loop above.
2978 // Emit them now, before the function that uses them is emitted. But,
2979 // be careful not to emit them twice.
2980 std::vector<Function*>::iterator I = prototypesToGen.begin();
2981 std::vector<Function*>::iterator E = prototypesToGen.end();
2982 for ( ; I != E; ++I) {
2983 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2985 printFunctionSignature(*I, true);
2991 void CWriter::visitCallInst(CallInst &I) {
2992 if (isa<InlineAsm>(I.getOperand(0)))
2993 return visitInlineAsm(I);
2995 bool WroteCallee = false;
2997 // Handle intrinsic function calls first...
2998 if (Function *F = I.getCalledFunction())
2999 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3000 if (visitBuiltinCall(I, ID, WroteCallee))
3003 Value *Callee = I.getCalledValue();
3005 const PointerType *PTy = cast<PointerType>(Callee->getType());
3006 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3008 // If this is a call to a struct-return function, assign to the first
3009 // parameter instead of passing it to the call.
3010 const AttrListPtr &PAL = I.getAttributes();
3011 bool hasByVal = I.hasByValArgument();
3012 bool isStructRet = I.hasStructRetAttr();
3014 writeOperandDeref(I.getOperand(1));
3018 if (I.isTailCall()) Out << " /*tail*/ ";
3021 // If this is an indirect call to a struct return function, we need to cast
3022 // the pointer. Ditto for indirect calls with byval arguments.
3023 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
3025 // GCC is a real PITA. It does not permit codegening casts of functions to
3026 // function pointers if they are in a call (it generates a trap instruction
3027 // instead!). We work around this by inserting a cast to void* in between
3028 // the function and the function pointer cast. Unfortunately, we can't just
3029 // form the constant expression here, because the folder will immediately
3032 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3033 // that void* and function pointers have the same size. :( To deal with this
3034 // in the common case, we handle casts where the number of arguments passed
3037 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3039 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3045 // Ok, just cast the pointer type.
3048 printStructReturnPointerFunctionType(Out, PAL,
3049 cast<PointerType>(I.getCalledValue()->getType()));
3051 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3053 printType(Out, I.getCalledValue()->getType());
3056 writeOperand(Callee);
3057 if (NeedsCast) Out << ')';
3062 unsigned NumDeclaredParams = FTy->getNumParams();
3064 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3066 if (isStructRet) { // Skip struct return argument.
3071 bool PrintedArg = false;
3072 for (; AI != AE; ++AI, ++ArgNo) {
3073 if (PrintedArg) Out << ", ";
3074 if (ArgNo < NumDeclaredParams &&
3075 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3077 printType(Out, FTy->getParamType(ArgNo),
3078 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3081 // Check if the argument is expected to be passed by value.
3082 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3083 writeOperandDeref(*AI);
3091 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3092 /// if the entire call is handled, return false it it wasn't handled, and
3093 /// optionally set 'WroteCallee' if the callee has already been printed out.
3094 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3095 bool &WroteCallee) {
3098 // If this is an intrinsic that directly corresponds to a GCC
3099 // builtin, we emit it here.
3100 const char *BuiltinName = "";
3101 Function *F = I.getCalledFunction();
3102 #define GET_GCC_BUILTIN_NAME
3103 #include "llvm/Intrinsics.gen"
3104 #undef GET_GCC_BUILTIN_NAME
3105 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3111 case Intrinsic::memory_barrier:
3112 Out << "__sync_synchronize()";
3114 case Intrinsic::vastart:
3117 Out << "va_start(*(va_list*)";
3118 writeOperand(I.getOperand(1));
3120 // Output the last argument to the enclosing function.
3121 if (I.getParent()->getParent()->arg_empty()) {
3123 raw_string_ostream Msg(msg);
3124 Msg << "The C backend does not currently support zero "
3125 << "argument varargs functions, such as '"
3126 << I.getParent()->getParent()->getName() << "'!";
3127 llvm_report_error(Msg.str());
3129 writeOperand(--I.getParent()->getParent()->arg_end());
3132 case Intrinsic::vaend:
3133 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3134 Out << "0; va_end(*(va_list*)";
3135 writeOperand(I.getOperand(1));
3138 Out << "va_end(*(va_list*)0)";
3141 case Intrinsic::vacopy:
3143 Out << "va_copy(*(va_list*)";
3144 writeOperand(I.getOperand(1));
3145 Out << ", *(va_list*)";
3146 writeOperand(I.getOperand(2));
3149 case Intrinsic::returnaddress:
3150 Out << "__builtin_return_address(";
3151 writeOperand(I.getOperand(1));
3154 case Intrinsic::frameaddress:
3155 Out << "__builtin_frame_address(";
3156 writeOperand(I.getOperand(1));
3159 case Intrinsic::powi:
3160 Out << "__builtin_powi(";
3161 writeOperand(I.getOperand(1));
3163 writeOperand(I.getOperand(2));
3166 case Intrinsic::setjmp:
3167 Out << "setjmp(*(jmp_buf*)";
3168 writeOperand(I.getOperand(1));
3171 case Intrinsic::longjmp:
3172 Out << "longjmp(*(jmp_buf*)";
3173 writeOperand(I.getOperand(1));
3175 writeOperand(I.getOperand(2));
3178 case Intrinsic::prefetch:
3179 Out << "LLVM_PREFETCH((const void *)";
3180 writeOperand(I.getOperand(1));
3182 writeOperand(I.getOperand(2));
3184 writeOperand(I.getOperand(3));
3187 case Intrinsic::stacksave:
3188 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3189 // to work around GCC bugs (see PR1809).
3190 Out << "0; *((void**)&" << GetValueName(&I)
3191 << ") = __builtin_stack_save()";
3193 case Intrinsic::x86_sse_cmp_ss:
3194 case Intrinsic::x86_sse_cmp_ps:
3195 case Intrinsic::x86_sse2_cmp_sd:
3196 case Intrinsic::x86_sse2_cmp_pd:
3198 printType(Out, I.getType());
3200 // Multiple GCC builtins multiplex onto this intrinsic.
3201 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3202 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3203 case 0: Out << "__builtin_ia32_cmpeq"; break;
3204 case 1: Out << "__builtin_ia32_cmplt"; break;
3205 case 2: Out << "__builtin_ia32_cmple"; break;
3206 case 3: Out << "__builtin_ia32_cmpunord"; break;
3207 case 4: Out << "__builtin_ia32_cmpneq"; break;
3208 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3209 case 6: Out << "__builtin_ia32_cmpnle"; break;
3210 case 7: Out << "__builtin_ia32_cmpord"; break;
3212 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3216 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3222 writeOperand(I.getOperand(1));
3224 writeOperand(I.getOperand(2));
3227 case Intrinsic::ppc_altivec_lvsl:
3229 printType(Out, I.getType());
3231 Out << "__builtin_altivec_lvsl(0, (void*)";
3232 writeOperand(I.getOperand(1));
3238 //This converts the llvm constraint string to something gcc is expecting.
3239 //TODO: work out platform independent constraints and factor those out
3240 // of the per target tables
3241 // handle multiple constraint codes
3242 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3244 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3246 const char *const *table = 0;
3248 // Grab the translation table from MCAsmInfo if it exists.
3250 std::string Triple = TheModule->getTargetTriple();
3252 Triple = llvm::sys::getHostTriple();
3255 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3256 TAsm = Match->createAsmInfo(Triple);
3259 table = TAsm->getAsmCBE();
3261 // Search the translation table if it exists.
3262 for (int i = 0; table && table[i]; i += 2)
3263 if (c.Codes[0] == table[i])
3266 // Default is identity.
3270 //TODO: import logic from AsmPrinter.cpp
3271 static std::string gccifyAsm(std::string asmstr) {
3272 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3273 if (asmstr[i] == '\n')
3274 asmstr.replace(i, 1, "\\n");
3275 else if (asmstr[i] == '\t')
3276 asmstr.replace(i, 1, "\\t");
3277 else if (asmstr[i] == '$') {
3278 if (asmstr[i + 1] == '{') {
3279 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3280 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3281 std::string n = "%" +
3282 asmstr.substr(a + 1, b - a - 1) +
3283 asmstr.substr(i + 2, a - i - 2);
3284 asmstr.replace(i, b - i + 1, n);
3287 asmstr.replace(i, 1, "%");
3289 else if (asmstr[i] == '%')//grr
3290 { asmstr.replace(i, 1, "%%"); ++i;}
3295 //TODO: assumptions about what consume arguments from the call are likely wrong
3296 // handle communitivity
3297 void CWriter::visitInlineAsm(CallInst &CI) {
3298 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3299 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3301 std::vector<std::pair<Value*, int> > ResultVals;
3302 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3304 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3305 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3306 ResultVals.push_back(std::make_pair(&CI, (int)i));
3308 ResultVals.push_back(std::make_pair(&CI, -1));
3311 // Fix up the asm string for gcc and emit it.
3312 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3315 unsigned ValueCount = 0;
3316 bool IsFirst = true;
3318 // Convert over all the output constraints.
3319 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3320 E = Constraints.end(); I != E; ++I) {
3322 if (I->Type != InlineAsm::isOutput) {
3324 continue; // Ignore non-output constraints.
3327 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3328 std::string C = InterpretASMConstraint(*I);
3329 if (C.empty()) continue;
3340 if (ValueCount < ResultVals.size()) {
3341 DestVal = ResultVals[ValueCount].first;
3342 DestValNo = ResultVals[ValueCount].second;
3344 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3346 if (I->isEarlyClobber)
3349 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3350 if (DestValNo != -1)
3351 Out << ".field" << DestValNo; // Multiple retvals.
3357 // Convert over all the input constraints.
3361 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3362 E = Constraints.end(); I != E; ++I) {
3363 if (I->Type != InlineAsm::isInput) {
3365 continue; // Ignore non-input constraints.
3368 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3369 std::string C = InterpretASMConstraint(*I);
3370 if (C.empty()) continue;
3377 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3378 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3380 Out << "\"" << C << "\"(";
3382 writeOperand(SrcVal);
3384 writeOperandDeref(SrcVal);
3388 // Convert over the clobber constraints.
3390 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3391 E = Constraints.end(); I != E; ++I) {
3392 if (I->Type != InlineAsm::isClobber)
3393 continue; // Ignore non-input constraints.
3395 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3396 std::string C = InterpretASMConstraint(*I);
3397 if (C.empty()) continue;
3404 Out << '\"' << C << '"';
3410 void CWriter::visitAllocaInst(AllocaInst &I) {
3412 printType(Out, I.getType());
3413 Out << ") alloca(sizeof(";
3414 printType(Out, I.getType()->getElementType());
3416 if (I.isArrayAllocation()) {
3418 writeOperand(I.getOperand(0));
3423 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3424 gep_type_iterator E, bool Static) {
3426 // If there are no indices, just print out the pointer.
3432 // Find out if the last index is into a vector. If so, we have to print this
3433 // specially. Since vectors can't have elements of indexable type, only the
3434 // last index could possibly be of a vector element.
3435 const VectorType *LastIndexIsVector = 0;
3437 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3438 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3443 // If the last index is into a vector, we can't print it as &a[i][j] because
3444 // we can't index into a vector with j in GCC. Instead, emit this as
3445 // (((float*)&a[i])+j)
3446 if (LastIndexIsVector) {
3448 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3454 // If the first index is 0 (very typical) we can do a number of
3455 // simplifications to clean up the code.
3456 Value *FirstOp = I.getOperand();
3457 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3458 // First index isn't simple, print it the hard way.
3461 ++I; // Skip the zero index.
3463 // Okay, emit the first operand. If Ptr is something that is already address
3464 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3465 if (isAddressExposed(Ptr)) {
3466 writeOperandInternal(Ptr, Static);
3467 } else if (I != E && isa<StructType>(*I)) {
3468 // If we didn't already emit the first operand, see if we can print it as
3469 // P->f instead of "P[0].f"
3471 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3472 ++I; // eat the struct index as well.
3474 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3481 for (; I != E; ++I) {
3482 if (isa<StructType>(*I)) {
3483 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3484 } else if (isa<ArrayType>(*I)) {
3486 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3488 } else if (!isa<VectorType>(*I)) {
3490 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3493 // If the last index is into a vector, then print it out as "+j)". This
3494 // works with the 'LastIndexIsVector' code above.
3495 if (isa<Constant>(I.getOperand()) &&
3496 cast<Constant>(I.getOperand())->isNullValue()) {
3497 Out << "))"; // avoid "+0".
3500 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3508 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3509 bool IsVolatile, unsigned Alignment) {
3511 bool IsUnaligned = Alignment &&
3512 Alignment < TD->getABITypeAlignment(OperandType);
3516 if (IsVolatile || IsUnaligned) {
3519 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3520 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3523 if (IsVolatile) Out << "volatile ";
3529 writeOperand(Operand);
3531 if (IsVolatile || IsUnaligned) {
3538 void CWriter::visitLoadInst(LoadInst &I) {
3539 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3544 void CWriter::visitStoreInst(StoreInst &I) {
3545 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3546 I.isVolatile(), I.getAlignment());
3548 Value *Operand = I.getOperand(0);
3549 Constant *BitMask = 0;
3550 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3551 if (!ITy->isPowerOf2ByteWidth())
3552 // We have a bit width that doesn't match an even power-of-2 byte
3553 // size. Consequently we must & the value with the type's bit mask
3554 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3557 writeOperand(Operand);
3560 printConstant(BitMask, false);
3565 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3566 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3567 gep_type_end(I), false);
3570 void CWriter::visitVAArgInst(VAArgInst &I) {
3571 Out << "va_arg(*(va_list*)";
3572 writeOperand(I.getOperand(0));
3574 printType(Out, I.getType());
3578 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3579 const Type *EltTy = I.getType()->getElementType();
3580 writeOperand(I.getOperand(0));
3583 printType(Out, PointerType::getUnqual(EltTy));
3584 Out << ")(&" << GetValueName(&I) << "))[";
3585 writeOperand(I.getOperand(2));
3587 writeOperand(I.getOperand(1));
3591 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3592 // We know that our operand is not inlined.
3595 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3596 printType(Out, PointerType::getUnqual(EltTy));
3597 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3598 writeOperand(I.getOperand(1));
3602 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3604 printType(Out, SVI.getType());
3606 const VectorType *VT = SVI.getType();
3607 unsigned NumElts = VT->getNumElements();
3608 const Type *EltTy = VT->getElementType();
3610 for (unsigned i = 0; i != NumElts; ++i) {
3612 int SrcVal = SVI.getMaskValue(i);
3613 if ((unsigned)SrcVal >= NumElts*2) {
3614 Out << " 0/*undef*/ ";
3616 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3617 if (isa<Instruction>(Op)) {
3618 // Do an extractelement of this value from the appropriate input.
3620 printType(Out, PointerType::getUnqual(EltTy));
3621 Out << ")(&" << GetValueName(Op)
3622 << "))[" << (SrcVal & (NumElts-1)) << "]";
3623 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3626 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3635 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3636 // Start by copying the entire aggregate value into the result variable.
3637 writeOperand(IVI.getOperand(0));
3640 // Then do the insert to update the field.
3641 Out << GetValueName(&IVI);
3642 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3644 const Type *IndexedTy =
3645 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3646 if (isa<ArrayType>(IndexedTy))
3647 Out << ".array[" << *i << "]";
3649 Out << ".field" << *i;
3652 writeOperand(IVI.getOperand(1));
3655 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3657 if (isa<UndefValue>(EVI.getOperand(0))) {
3659 printType(Out, EVI.getType());
3660 Out << ") 0/*UNDEF*/";
3662 Out << GetValueName(EVI.getOperand(0));
3663 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3665 const Type *IndexedTy =
3666 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3667 if (isa<ArrayType>(IndexedTy))
3668 Out << ".array[" << *i << "]";
3670 Out << ".field" << *i;
3676 //===----------------------------------------------------------------------===//
3677 // External Interface declaration
3678 //===----------------------------------------------------------------------===//
3680 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3681 formatted_raw_ostream &o,
3682 CodeGenFileType FileType,
3683 CodeGenOpt::Level OptLevel) {
3684 if (FileType != TargetMachine::AssemblyFile) return true;
3686 PM.add(createGCLoweringPass());
3687 PM.add(createLowerInvokePass());
3688 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3689 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3690 PM.add(new CWriter(o));
3691 PM.add(createGCInfoDeleter());