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 class CBEMCAsmInfo : public MCAsmInfo {
65 PrivateGlobalPrefix = "";
68 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
69 /// any unnamed structure types that are used by the program, and merges
70 /// external functions with the same name.
72 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
75 CBackendNameAllUsedStructsAndMergeFunctions()
77 void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequired<FindUsedTypes>();
81 virtual const char *getPassName() const {
82 return "C backend type canonicalizer";
85 virtual bool runOnModule(Module &M);
88 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
90 /// CWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C translation unit.
92 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
93 formatted_raw_ostream &Out;
94 IntrinsicLowering *IL;
97 const Module *TheModule;
98 const MCAsmInfo* TAsm;
100 std::map<const Type *, std::string> TypeNames;
101 std::map<const ConstantFP *, unsigned> FPConstantMap;
102 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
103 std::set<const Argument*> ByValParams;
105 unsigned OpaqueCounter;
106 DenseMap<const Value*, unsigned> AnonValueNumbers;
107 unsigned NextAnonValueNumber;
111 explicit CWriter(formatted_raw_ostream &o)
112 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
113 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
117 virtual const char *getPassName() const { return "C backend"; }
119 void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.addRequired<LoopInfo>();
121 AU.setPreservesAll();
124 virtual bool doInitialization(Module &M);
126 bool runOnFunction(Function &F) {
127 // Do not codegen any 'available_externally' functions at all, they have
128 // definitions outside the translation unit.
129 if (F.hasAvailableExternallyLinkage())
132 LI = &getAnalysis<LoopInfo>();
134 // Get rid of intrinsics we can't handle.
137 // Output all floating point constants that cannot be printed accurately.
138 printFloatingPointConstants(F);
144 virtual bool doFinalization(Module &M) {
149 FPConstantMap.clear();
152 intrinsicPrototypesAlreadyGenerated.clear();
156 raw_ostream &printType(formatted_raw_ostream &Out,
158 bool isSigned = false,
159 const std::string &VariableName = "",
160 bool IgnoreName = false,
161 const AttrListPtr &PAL = AttrListPtr());
162 std::ostream &printType(std::ostream &Out, const Type *Ty,
163 bool isSigned = false,
164 const std::string &VariableName = "",
165 bool IgnoreName = false,
166 const AttrListPtr &PAL = AttrListPtr());
167 raw_ostream &printSimpleType(formatted_raw_ostream &Out,
170 const std::string &NameSoFar = "");
171 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
173 const std::string &NameSoFar = "");
175 void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
176 const AttrListPtr &PAL,
177 const PointerType *Ty);
179 /// writeOperandDeref - Print the result of dereferencing the specified
180 /// operand with '*'. This is equivalent to printing '*' then using
181 /// writeOperand, but avoids excess syntax in some cases.
182 void writeOperandDeref(Value *Operand) {
183 if (isAddressExposed(Operand)) {
184 // Already something with an address exposed.
185 writeOperandInternal(Operand);
188 writeOperand(Operand);
193 void writeOperand(Value *Operand, bool Static = false);
194 void writeInstComputationInline(Instruction &I);
195 void writeOperandInternal(Value *Operand, bool Static = false);
196 void writeOperandWithCast(Value* Operand, unsigned Opcode);
197 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
198 bool writeInstructionCast(const Instruction &I);
200 void writeMemoryAccess(Value *Operand, const Type *OperandType,
201 bool IsVolatile, unsigned Alignment);
204 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
206 void lowerIntrinsics(Function &F);
208 void printModule(Module *M);
209 void printModuleTypes(const TypeSymbolTable &ST);
210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
211 void printFloatingPointConstants(Function &F);
212 void printFloatingPointConstants(const Constant *C);
213 void printFunctionSignature(const Function *F, bool Prototype);
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
220 void printConstant(Constant *CPV, bool Static);
221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
252 // Don't inline a load across a store or other bad things!
255 // Must not be used in inline asm, extractelement, or shufflevector.
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
273 if (!AI) return false;
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
282 static bool isInlineAsm(const Instruction& I) {
283 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
294 void visitIndirectBrInst(IndirectBrInst &I);
295 void visitInvokeInst(InvokeInst &I) {
296 llvm_unreachable("Lowerinvoke pass didn't work!");
299 void visitUnwindInst(UnwindInst &I) {
300 llvm_unreachable("Lowerinvoke pass didn't work!");
302 void visitUnreachableInst(UnreachableInst &I);
304 void visitPHINode(PHINode &I);
305 void visitBinaryOperator(Instruction &I);
306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
309 void visitCastInst (CastInst &I);
310 void visitSelectInst(SelectInst &I);
311 void visitCallInst (CallInst &I);
312 void visitInlineAsm(CallInst &I);
313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
315 void visitAllocaInst(AllocaInst &I);
316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
321 void visitInsertElementInst(InsertElementInst &I);
322 void visitExtractElementInst(ExtractElementInst &I);
323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
328 void visitInstruction(Instruction &I) {
330 errs() << "C Writer does not know about " << I;
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
345 gep_type_iterator E, bool Static);
347 std::string GetValueName(const Value *Operand);
351 char CWriter::ID = 0;
354 static std::string Mangle(const std::string &S) {
355 SmallString<52> Result;
356 Mangler::appendMangledName(Result, S, 0);
357 return std::string(Result.begin(), Result.end());
361 /// This method inserts names for any unnamed structure types that are used by
362 /// the program, and removes names from structure types that are not used by the
365 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
366 // Get a set of types that are used by the program...
367 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
369 // Loop over the module symbol table, removing types from UT that are
370 // already named, and removing names for types that are not used.
372 TypeSymbolTable &TST = M.getTypeSymbolTable();
373 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
375 TypeSymbolTable::iterator I = TI++;
377 // If this isn't a struct or array type, remove it from our set of types
378 // to name. This simplifies emission later.
379 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
380 !isa<ArrayType>(I->second)) {
383 // If this is not used, remove it from the symbol table.
384 std::set<const Type *>::iterator UTI = UT.find(I->second);
388 UT.erase(UTI); // Only keep one name for this type.
392 // UT now contains types that are not named. Loop over it, naming
395 bool Changed = false;
396 unsigned RenameCounter = 0;
397 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
399 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
400 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
406 // Loop over all external functions and globals. If we have two with
407 // identical names, merge them.
408 // FIXME: This code should disappear when we don't allow values with the same
409 // names when they have different types!
410 std::map<std::string, GlobalValue*> ExtSymbols;
411 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
413 if (GV->isDeclaration() && GV->hasName()) {
414 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
415 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
417 // Found a conflict, replace this global with the previous one.
418 GlobalValue *OldGV = X.first->second;
419 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
420 GV->eraseFromParent();
425 // Do the same for globals.
426 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
428 GlobalVariable *GV = I++;
429 if (GV->isDeclaration() && GV->hasName()) {
430 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
431 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
433 // Found a conflict, replace this global with the previous one.
434 GlobalValue *OldGV = X.first->second;
435 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
436 GV->eraseFromParent();
445 /// printStructReturnPointerFunctionType - This is like printType for a struct
446 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
447 /// print it as "Struct (*)(...)", for struct return functions.
448 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
449 const AttrListPtr &PAL,
450 const PointerType *TheTy) {
451 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
452 std::stringstream FunctionInnards;
453 FunctionInnards << " (*) (";
454 bool PrintedType = false;
456 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
457 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
459 for (++I, ++Idx; I != E; ++I, ++Idx) {
461 FunctionInnards << ", ";
462 const Type *ArgTy = *I;
463 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
464 assert(isa<PointerType>(ArgTy));
465 ArgTy = cast<PointerType>(ArgTy)->getElementType();
467 printType(FunctionInnards, ArgTy,
468 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
471 if (FTy->isVarArg()) {
473 FunctionInnards << ", ...";
474 } else if (!PrintedType) {
475 FunctionInnards << "void";
477 FunctionInnards << ')';
478 std::string tstr = FunctionInnards.str();
479 printType(Out, RetTy,
480 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
484 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
486 const std::string &NameSoFar) {
487 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
488 "Invalid type for printSimpleType");
489 switch (Ty->getTypeID()) {
490 case Type::VoidTyID: return Out << "void " << NameSoFar;
491 case Type::IntegerTyID: {
492 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
494 return Out << "bool " << NameSoFar;
495 else if (NumBits <= 8)
496 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
497 else if (NumBits <= 16)
498 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
499 else if (NumBits <= 32)
500 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
501 else if (NumBits <= 64)
502 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
504 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
505 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
508 case Type::FloatTyID: return Out << "float " << NameSoFar;
509 case Type::DoubleTyID: return Out << "double " << NameSoFar;
510 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
511 // present matches host 'long double'.
512 case Type::X86_FP80TyID:
513 case Type::PPC_FP128TyID:
514 case Type::FP128TyID: return Out << "long double " << NameSoFar;
516 case Type::VectorTyID: {
517 const VectorType *VTy = cast<VectorType>(Ty);
518 return printSimpleType(Out, VTy->getElementType(), isSigned,
519 " __attribute__((vector_size(" +
520 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
525 errs() << "Unknown primitive type: " << *Ty << "\n";
532 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
533 const std::string &NameSoFar) {
534 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
535 "Invalid type for printSimpleType");
536 switch (Ty->getTypeID()) {
537 case Type::VoidTyID: return Out << "void " << NameSoFar;
538 case Type::IntegerTyID: {
539 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
541 return Out << "bool " << NameSoFar;
542 else if (NumBits <= 8)
543 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
544 else if (NumBits <= 16)
545 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
546 else if (NumBits <= 32)
547 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
548 else if (NumBits <= 64)
549 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
551 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
552 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
555 case Type::FloatTyID: return Out << "float " << NameSoFar;
556 case Type::DoubleTyID: return Out << "double " << NameSoFar;
557 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
558 // present matches host 'long double'.
559 case Type::X86_FP80TyID:
560 case Type::PPC_FP128TyID:
561 case Type::FP128TyID: return Out << "long double " << NameSoFar;
563 case Type::VectorTyID: {
564 const VectorType *VTy = cast<VectorType>(Ty);
565 return printSimpleType(Out, VTy->getElementType(), isSigned,
566 " __attribute__((vector_size(" +
567 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
572 errs() << "Unknown primitive type: " << *Ty << "\n";
578 // Pass the Type* and the variable name and this prints out the variable
581 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
583 bool isSigned, const std::string &NameSoFar,
584 bool IgnoreName, const AttrListPtr &PAL) {
585 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
586 printSimpleType(Out, Ty, isSigned, NameSoFar);
590 // Check to see if the type is named.
591 if (!IgnoreName || isa<OpaqueType>(Ty)) {
592 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
593 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
596 switch (Ty->getTypeID()) {
597 case Type::FunctionTyID: {
598 const FunctionType *FTy = cast<FunctionType>(Ty);
599 std::stringstream FunctionInnards;
600 FunctionInnards << " (" << NameSoFar << ") (";
602 for (FunctionType::param_iterator I = FTy->param_begin(),
603 E = FTy->param_end(); I != E; ++I) {
604 const Type *ArgTy = *I;
605 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
606 assert(isa<PointerType>(ArgTy));
607 ArgTy = cast<PointerType>(ArgTy)->getElementType();
609 if (I != FTy->param_begin())
610 FunctionInnards << ", ";
611 printType(FunctionInnards, ArgTy,
612 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
615 if (FTy->isVarArg()) {
616 if (FTy->getNumParams())
617 FunctionInnards << ", ...";
618 } else if (!FTy->getNumParams()) {
619 FunctionInnards << "void";
621 FunctionInnards << ')';
622 std::string tstr = FunctionInnards.str();
623 printType(Out, FTy->getReturnType(),
624 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
627 case Type::StructTyID: {
628 const StructType *STy = cast<StructType>(Ty);
629 Out << NameSoFar + " {\n";
631 for (StructType::element_iterator I = STy->element_begin(),
632 E = STy->element_end(); I != E; ++I) {
634 printType(Out, *I, false, "field" + utostr(Idx++));
639 Out << " __attribute__ ((packed))";
643 case Type::PointerTyID: {
644 const PointerType *PTy = cast<PointerType>(Ty);
645 std::string ptrName = "*" + NameSoFar;
647 if (isa<ArrayType>(PTy->getElementType()) ||
648 isa<VectorType>(PTy->getElementType()))
649 ptrName = "(" + ptrName + ")";
652 // Must be a function ptr cast!
653 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
654 return printType(Out, PTy->getElementType(), false, ptrName);
657 case Type::ArrayTyID: {
658 const ArrayType *ATy = cast<ArrayType>(Ty);
659 unsigned NumElements = ATy->getNumElements();
660 if (NumElements == 0) NumElements = 1;
661 // Arrays are wrapped in structs to allow them to have normal
662 // value semantics (avoiding the array "decay").
663 Out << NameSoFar << " { ";
664 printType(Out, ATy->getElementType(), false,
665 "array[" + utostr(NumElements) + "]");
669 case Type::OpaqueTyID: {
670 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
671 assert(TypeNames.find(Ty) == TypeNames.end());
672 TypeNames[Ty] = TyName;
673 return Out << TyName << ' ' << NameSoFar;
676 llvm_unreachable("Unhandled case in getTypeProps!");
682 // Pass the Type* and the variable name and this prints out the variable
685 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
686 bool isSigned, const std::string &NameSoFar,
687 bool IgnoreName, const AttrListPtr &PAL) {
688 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
689 printSimpleType(Out, Ty, isSigned, NameSoFar);
693 // Check to see if the type is named.
694 if (!IgnoreName || isa<OpaqueType>(Ty)) {
695 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
696 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
699 switch (Ty->getTypeID()) {
700 case Type::FunctionTyID: {
701 const FunctionType *FTy = cast<FunctionType>(Ty);
702 std::stringstream FunctionInnards;
703 FunctionInnards << " (" << NameSoFar << ") (";
705 for (FunctionType::param_iterator I = FTy->param_begin(),
706 E = FTy->param_end(); I != E; ++I) {
707 const Type *ArgTy = *I;
708 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
709 assert(isa<PointerType>(ArgTy));
710 ArgTy = cast<PointerType>(ArgTy)->getElementType();
712 if (I != FTy->param_begin())
713 FunctionInnards << ", ";
714 printType(FunctionInnards, ArgTy,
715 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
718 if (FTy->isVarArg()) {
719 if (FTy->getNumParams())
720 FunctionInnards << ", ...";
721 } else if (!FTy->getNumParams()) {
722 FunctionInnards << "void";
724 FunctionInnards << ')';
725 std::string tstr = FunctionInnards.str();
726 printType(Out, FTy->getReturnType(),
727 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
730 case Type::StructTyID: {
731 const StructType *STy = cast<StructType>(Ty);
732 Out << NameSoFar + " {\n";
734 for (StructType::element_iterator I = STy->element_begin(),
735 E = STy->element_end(); I != E; ++I) {
737 printType(Out, *I, false, "field" + utostr(Idx++));
742 Out << " __attribute__ ((packed))";
746 case Type::PointerTyID: {
747 const PointerType *PTy = cast<PointerType>(Ty);
748 std::string ptrName = "*" + NameSoFar;
750 if (isa<ArrayType>(PTy->getElementType()) ||
751 isa<VectorType>(PTy->getElementType()))
752 ptrName = "(" + ptrName + ")";
755 // Must be a function ptr cast!
756 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
757 return printType(Out, PTy->getElementType(), false, ptrName);
760 case Type::ArrayTyID: {
761 const ArrayType *ATy = cast<ArrayType>(Ty);
762 unsigned NumElements = ATy->getNumElements();
763 if (NumElements == 0) NumElements = 1;
764 // Arrays are wrapped in structs to allow them to have normal
765 // value semantics (avoiding the array "decay").
766 Out << NameSoFar << " { ";
767 printType(Out, ATy->getElementType(), false,
768 "array[" + utostr(NumElements) + "]");
772 case Type::OpaqueTyID: {
773 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
774 assert(TypeNames.find(Ty) == TypeNames.end());
775 TypeNames[Ty] = TyName;
776 return Out << TyName << ' ' << NameSoFar;
779 llvm_unreachable("Unhandled case in getTypeProps!");
785 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
787 // As a special case, print the array as a string if it is an array of
788 // ubytes or an array of sbytes with positive values.
790 const Type *ETy = CPA->getType()->getElementType();
791 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
792 ETy == Type::getInt8Ty(CPA->getContext()));
794 // Make sure the last character is a null char, as automatically added by C
795 if (isString && (CPA->getNumOperands() == 0 ||
796 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
801 // Keep track of whether the last number was a hexadecimal escape
802 bool LastWasHex = false;
804 // Do not include the last character, which we know is null
805 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
806 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
808 // Print it out literally if it is a printable character. The only thing
809 // to be careful about is when the last letter output was a hex escape
810 // code, in which case we have to be careful not to print out hex digits
811 // explicitly (the C compiler thinks it is a continuation of the previous
812 // character, sheesh...)
814 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
816 if (C == '"' || C == '\\')
817 Out << "\\" << (char)C;
823 case '\n': Out << "\\n"; break;
824 case '\t': Out << "\\t"; break;
825 case '\r': Out << "\\r"; break;
826 case '\v': Out << "\\v"; break;
827 case '\a': Out << "\\a"; break;
828 case '\"': Out << "\\\""; break;
829 case '\'': Out << "\\\'"; break;
832 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
833 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
842 if (CPA->getNumOperands()) {
844 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
845 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
847 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
854 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
856 if (CP->getNumOperands()) {
858 printConstant(cast<Constant>(CP->getOperand(0)), Static);
859 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
861 printConstant(cast<Constant>(CP->getOperand(i)), Static);
867 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
868 // textually as a double (rather than as a reference to a stack-allocated
869 // variable). We decide this by converting CFP to a string and back into a
870 // double, and then checking whether the conversion results in a bit-equal
871 // double to the original value of CFP. This depends on us and the target C
872 // compiler agreeing on the conversion process (which is pretty likely since we
873 // only deal in IEEE FP).
875 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
877 // Do long doubles in hex for now.
878 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
879 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
881 APFloat APF = APFloat(CFP->getValueAPF()); // copy
882 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
883 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
884 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
886 sprintf(Buffer, "%a", APF.convertToDouble());
887 if (!strncmp(Buffer, "0x", 2) ||
888 !strncmp(Buffer, "-0x", 3) ||
889 !strncmp(Buffer, "+0x", 3))
890 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
893 std::string StrVal = ftostr(APF);
895 while (StrVal[0] == ' ')
896 StrVal.erase(StrVal.begin());
898 // Check to make sure that the stringized number is not some string like "Inf"
899 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
900 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
901 ((StrVal[0] == '-' || StrVal[0] == '+') &&
902 (StrVal[1] >= '0' && StrVal[1] <= '9')))
903 // Reparse stringized version!
904 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
909 /// Print out the casting for a cast operation. This does the double casting
910 /// necessary for conversion to the destination type, if necessary.
911 /// @brief Print a cast
912 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
913 // Print the destination type cast
915 case Instruction::UIToFP:
916 case Instruction::SIToFP:
917 case Instruction::IntToPtr:
918 case Instruction::Trunc:
919 case Instruction::BitCast:
920 case Instruction::FPExt:
921 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
923 printType(Out, DstTy);
926 case Instruction::ZExt:
927 case Instruction::PtrToInt:
928 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
930 printSimpleType(Out, DstTy, false);
933 case Instruction::SExt:
934 case Instruction::FPToSI: // For these, make sure we get a signed dest
936 printSimpleType(Out, DstTy, true);
940 llvm_unreachable("Invalid cast opcode");
943 // Print the source type cast
945 case Instruction::UIToFP:
946 case Instruction::ZExt:
948 printSimpleType(Out, SrcTy, false);
951 case Instruction::SIToFP:
952 case Instruction::SExt:
954 printSimpleType(Out, SrcTy, true);
957 case Instruction::IntToPtr:
958 case Instruction::PtrToInt:
959 // Avoid "cast to pointer from integer of different size" warnings
960 Out << "(unsigned long)";
962 case Instruction::Trunc:
963 case Instruction::BitCast:
964 case Instruction::FPExt:
965 case Instruction::FPTrunc:
966 case Instruction::FPToSI:
967 case Instruction::FPToUI:
968 break; // These don't need a source cast.
970 llvm_unreachable("Invalid cast opcode");
975 // printConstant - The LLVM Constant to C Constant converter.
976 void CWriter::printConstant(Constant *CPV, bool Static) {
977 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
978 switch (CE->getOpcode()) {
979 case Instruction::Trunc:
980 case Instruction::ZExt:
981 case Instruction::SExt:
982 case Instruction::FPTrunc:
983 case Instruction::FPExt:
984 case Instruction::UIToFP:
985 case Instruction::SIToFP:
986 case Instruction::FPToUI:
987 case Instruction::FPToSI:
988 case Instruction::PtrToInt:
989 case Instruction::IntToPtr:
990 case Instruction::BitCast:
992 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
993 if (CE->getOpcode() == Instruction::SExt &&
994 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
995 // Make sure we really sext from bool here by subtracting from 0
998 printConstant(CE->getOperand(0), Static);
999 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
1000 (CE->getOpcode() == Instruction::Trunc ||
1001 CE->getOpcode() == Instruction::FPToUI ||
1002 CE->getOpcode() == Instruction::FPToSI ||
1003 CE->getOpcode() == Instruction::PtrToInt)) {
1004 // Make sure we really truncate to bool here by anding with 1
1010 case Instruction::GetElementPtr:
1012 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1013 gep_type_end(CPV), Static);
1016 case Instruction::Select:
1018 printConstant(CE->getOperand(0), Static);
1020 printConstant(CE->getOperand(1), Static);
1022 printConstant(CE->getOperand(2), Static);
1025 case Instruction::Add:
1026 case Instruction::FAdd:
1027 case Instruction::Sub:
1028 case Instruction::FSub:
1029 case Instruction::Mul:
1030 case Instruction::FMul:
1031 case Instruction::SDiv:
1032 case Instruction::UDiv:
1033 case Instruction::FDiv:
1034 case Instruction::URem:
1035 case Instruction::SRem:
1036 case Instruction::FRem:
1037 case Instruction::And:
1038 case Instruction::Or:
1039 case Instruction::Xor:
1040 case Instruction::ICmp:
1041 case Instruction::Shl:
1042 case Instruction::LShr:
1043 case Instruction::AShr:
1046 bool NeedsClosingParens = printConstExprCast(CE, Static);
1047 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1048 switch (CE->getOpcode()) {
1049 case Instruction::Add:
1050 case Instruction::FAdd: Out << " + "; break;
1051 case Instruction::Sub:
1052 case Instruction::FSub: Out << " - "; break;
1053 case Instruction::Mul:
1054 case Instruction::FMul: Out << " * "; break;
1055 case Instruction::URem:
1056 case Instruction::SRem:
1057 case Instruction::FRem: Out << " % "; break;
1058 case Instruction::UDiv:
1059 case Instruction::SDiv:
1060 case Instruction::FDiv: Out << " / "; break;
1061 case Instruction::And: Out << " & "; break;
1062 case Instruction::Or: Out << " | "; break;
1063 case Instruction::Xor: Out << " ^ "; break;
1064 case Instruction::Shl: Out << " << "; break;
1065 case Instruction::LShr:
1066 case Instruction::AShr: Out << " >> "; break;
1067 case Instruction::ICmp:
1068 switch (CE->getPredicate()) {
1069 case ICmpInst::ICMP_EQ: Out << " == "; break;
1070 case ICmpInst::ICMP_NE: Out << " != "; break;
1071 case ICmpInst::ICMP_SLT:
1072 case ICmpInst::ICMP_ULT: Out << " < "; break;
1073 case ICmpInst::ICMP_SLE:
1074 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1075 case ICmpInst::ICMP_SGT:
1076 case ICmpInst::ICMP_UGT: Out << " > "; break;
1077 case ICmpInst::ICMP_SGE:
1078 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1079 default: llvm_unreachable("Illegal ICmp predicate");
1082 default: llvm_unreachable("Illegal opcode here!");
1084 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1085 if (NeedsClosingParens)
1090 case Instruction::FCmp: {
1092 bool NeedsClosingParens = printConstExprCast(CE, Static);
1093 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1095 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1099 switch (CE->getPredicate()) {
1100 default: llvm_unreachable("Illegal FCmp predicate");
1101 case FCmpInst::FCMP_ORD: op = "ord"; break;
1102 case FCmpInst::FCMP_UNO: op = "uno"; break;
1103 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1104 case FCmpInst::FCMP_UNE: op = "une"; break;
1105 case FCmpInst::FCMP_ULT: op = "ult"; break;
1106 case FCmpInst::FCMP_ULE: op = "ule"; break;
1107 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1108 case FCmpInst::FCMP_UGE: op = "uge"; break;
1109 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1110 case FCmpInst::FCMP_ONE: op = "one"; break;
1111 case FCmpInst::FCMP_OLT: op = "olt"; break;
1112 case FCmpInst::FCMP_OLE: op = "ole"; break;
1113 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1114 case FCmpInst::FCMP_OGE: op = "oge"; break;
1116 Out << "llvm_fcmp_" << op << "(";
1117 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1119 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1122 if (NeedsClosingParens)
1129 errs() << "CWriter Error: Unhandled constant expression: "
1132 llvm_unreachable(0);
1134 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1136 printType(Out, CPV->getType()); // sign doesn't matter
1137 Out << ")/*UNDEF*/";
1138 if (!isa<VectorType>(CPV->getType())) {
1146 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1147 const Type* Ty = CI->getType();
1148 if (Ty == Type::getInt1Ty(CPV->getContext()))
1149 Out << (CI->getZExtValue() ? '1' : '0');
1150 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1151 Out << CI->getZExtValue() << 'u';
1152 else if (Ty->getPrimitiveSizeInBits() > 32)
1153 Out << CI->getZExtValue() << "ull";
1156 printSimpleType(Out, Ty, false) << ')';
1157 if (CI->isMinValue(true))
1158 Out << CI->getZExtValue() << 'u';
1160 Out << CI->getSExtValue();
1166 switch (CPV->getType()->getTypeID()) {
1167 case Type::FloatTyID:
1168 case Type::DoubleTyID:
1169 case Type::X86_FP80TyID:
1170 case Type::PPC_FP128TyID:
1171 case Type::FP128TyID: {
1172 ConstantFP *FPC = cast<ConstantFP>(CPV);
1173 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1174 if (I != FPConstantMap.end()) {
1175 // Because of FP precision problems we must load from a stack allocated
1176 // value that holds the value in hex.
1177 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1179 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1182 << "*)&FPConstant" << I->second << ')';
1185 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1186 V = FPC->getValueAPF().convertToFloat();
1187 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1188 V = FPC->getValueAPF().convertToDouble();
1190 // Long double. Convert the number to double, discarding precision.
1191 // This is not awesome, but it at least makes the CBE output somewhat
1193 APFloat Tmp = FPC->getValueAPF();
1195 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1196 V = Tmp.convertToDouble();
1202 // FIXME the actual NaN bits should be emitted.
1203 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1205 const unsigned long QuietNaN = 0x7ff8UL;
1206 //const unsigned long SignalNaN = 0x7ff4UL;
1208 // We need to grab the first part of the FP #
1211 uint64_t ll = DoubleToBits(V);
1212 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1214 std::string Num(&Buffer[0], &Buffer[6]);
1215 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1217 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1218 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1219 << Buffer << "\") /*nan*/ ";
1221 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1222 << Buffer << "\") /*nan*/ ";
1223 } else if (IsInf(V)) {
1225 if (V < 0) Out << '-';
1226 Out << "LLVM_INF" <<
1227 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1231 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1232 // Print out the constant as a floating point number.
1234 sprintf(Buffer, "%a", V);
1237 Num = ftostr(FPC->getValueAPF());
1245 case Type::ArrayTyID:
1246 // Use C99 compound expression literal initializer syntax.
1249 printType(Out, CPV->getType());
1252 Out << "{ "; // Arrays are wrapped in struct types.
1253 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1254 printConstantArray(CA, Static);
1256 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1257 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1259 if (AT->getNumElements()) {
1261 Constant *CZ = Constant::getNullValue(AT->getElementType());
1262 printConstant(CZ, Static);
1263 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1265 printConstant(CZ, Static);
1270 Out << " }"; // Arrays are wrapped in struct types.
1273 case Type::VectorTyID:
1274 // Use C99 compound expression literal initializer syntax.
1277 printType(Out, CPV->getType());
1280 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1281 printConstantVector(CV, Static);
1283 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1284 const VectorType *VT = cast<VectorType>(CPV->getType());
1286 Constant *CZ = Constant::getNullValue(VT->getElementType());
1287 printConstant(CZ, Static);
1288 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1290 printConstant(CZ, Static);
1296 case Type::StructTyID:
1297 // Use C99 compound expression literal initializer syntax.
1300 printType(Out, CPV->getType());
1303 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1304 const StructType *ST = cast<StructType>(CPV->getType());
1306 if (ST->getNumElements()) {
1308 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1309 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1311 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1317 if (CPV->getNumOperands()) {
1319 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1320 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1322 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1329 case Type::PointerTyID:
1330 if (isa<ConstantPointerNull>(CPV)) {
1332 printType(Out, CPV->getType()); // sign doesn't matter
1333 Out << ")/*NULL*/0)";
1335 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1336 writeOperand(GV, Static);
1342 errs() << "Unknown constant type: " << *CPV << "\n";
1344 llvm_unreachable(0);
1348 // Some constant expressions need to be casted back to the original types
1349 // because their operands were casted to the expected type. This function takes
1350 // care of detecting that case and printing the cast for the ConstantExpr.
1351 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1352 bool NeedsExplicitCast = false;
1353 const Type *Ty = CE->getOperand(0)->getType();
1354 bool TypeIsSigned = false;
1355 switch (CE->getOpcode()) {
1356 case Instruction::Add:
1357 case Instruction::Sub:
1358 case Instruction::Mul:
1359 // We need to cast integer arithmetic so that it is always performed
1360 // as unsigned, to avoid undefined behavior on overflow.
1361 case Instruction::LShr:
1362 case Instruction::URem:
1363 case Instruction::UDiv: NeedsExplicitCast = true; break;
1364 case Instruction::AShr:
1365 case Instruction::SRem:
1366 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1367 case Instruction::SExt:
1369 NeedsExplicitCast = true;
1370 TypeIsSigned = true;
1372 case Instruction::ZExt:
1373 case Instruction::Trunc:
1374 case Instruction::FPTrunc:
1375 case Instruction::FPExt:
1376 case Instruction::UIToFP:
1377 case Instruction::SIToFP:
1378 case Instruction::FPToUI:
1379 case Instruction::FPToSI:
1380 case Instruction::PtrToInt:
1381 case Instruction::IntToPtr:
1382 case Instruction::BitCast:
1384 NeedsExplicitCast = true;
1388 if (NeedsExplicitCast) {
1390 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
1391 printSimpleType(Out, Ty, TypeIsSigned);
1393 printType(Out, Ty); // not integer, sign doesn't matter
1396 return NeedsExplicitCast;
1399 // Print a constant assuming that it is the operand for a given Opcode. The
1400 // opcodes that care about sign need to cast their operands to the expected
1401 // type before the operation proceeds. This function does the casting.
1402 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1404 // Extract the operand's type, we'll need it.
1405 const Type* OpTy = CPV->getType();
1407 // Indicate whether to do the cast or not.
1408 bool shouldCast = false;
1409 bool typeIsSigned = false;
1411 // Based on the Opcode for which this Constant is being written, determine
1412 // the new type to which the operand should be casted by setting the value
1413 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1417 // for most instructions, it doesn't matter
1419 case Instruction::Add:
1420 case Instruction::Sub:
1421 case Instruction::Mul:
1422 // We need to cast integer arithmetic so that it is always performed
1423 // as unsigned, to avoid undefined behavior on overflow.
1424 case Instruction::LShr:
1425 case Instruction::UDiv:
1426 case Instruction::URem:
1429 case Instruction::AShr:
1430 case Instruction::SDiv:
1431 case Instruction::SRem:
1433 typeIsSigned = true;
1437 // Write out the casted constant if we should, otherwise just write the
1441 printSimpleType(Out, OpTy, typeIsSigned);
1443 printConstant(CPV, false);
1446 printConstant(CPV, false);
1449 std::string CWriter::GetValueName(const Value *Operand) {
1450 // Mangle globals with the standard mangler interface for LLC compatibility.
1451 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1452 SmallString<128> Str;
1453 Mang->getNameWithPrefix(Str, GV, false);
1454 return Str.str().str();
1457 std::string Name = Operand->getName();
1459 if (Name.empty()) { // Assign unique names to local temporaries.
1460 unsigned &No = AnonValueNumbers[Operand];
1462 No = ++NextAnonValueNumber;
1463 Name = "tmp__" + utostr(No);
1466 std::string VarName;
1467 VarName.reserve(Name.capacity());
1469 for (std::string::iterator I = Name.begin(), E = Name.end();
1473 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1474 (ch >= '0' && ch <= '9') || ch == '_')) {
1476 sprintf(buffer, "_%x_", ch);
1482 return "llvm_cbe_" + VarName;
1485 /// writeInstComputationInline - Emit the computation for the specified
1486 /// instruction inline, with no destination provided.
1487 void CWriter::writeInstComputationInline(Instruction &I) {
1488 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1490 const Type *Ty = I.getType();
1491 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1492 Ty!=Type::getInt8Ty(I.getContext()) &&
1493 Ty!=Type::getInt16Ty(I.getContext()) &&
1494 Ty!=Type::getInt32Ty(I.getContext()) &&
1495 Ty!=Type::getInt64Ty(I.getContext()))) {
1496 llvm_report_error("The C backend does not currently support integer "
1497 "types of widths other than 1, 8, 16, 32, 64.\n"
1498 "This is being tracked as PR 4158.");
1501 // If this is a non-trivial bool computation, make sure to truncate down to
1502 // a 1 bit value. This is important because we want "add i1 x, y" to return
1503 // "0" when x and y are true, not "2" for example.
1504 bool NeedBoolTrunc = false;
1505 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1506 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1507 NeedBoolTrunc = true;
1519 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1520 if (Instruction *I = dyn_cast<Instruction>(Operand))
1521 // Should we inline this instruction to build a tree?
1522 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1524 writeInstComputationInline(*I);
1529 Constant* CPV = dyn_cast<Constant>(Operand);
1531 if (CPV && !isa<GlobalValue>(CPV))
1532 printConstant(CPV, Static);
1534 Out << GetValueName(Operand);
1537 void CWriter::writeOperand(Value *Operand, bool Static) {
1538 bool isAddressImplicit = isAddressExposed(Operand);
1539 if (isAddressImplicit)
1540 Out << "(&"; // Global variables are referenced as their addresses by llvm
1542 writeOperandInternal(Operand, Static);
1544 if (isAddressImplicit)
1548 // Some instructions need to have their result value casted back to the
1549 // original types because their operands were casted to the expected type.
1550 // This function takes care of detecting that case and printing the cast
1551 // for the Instruction.
1552 bool CWriter::writeInstructionCast(const Instruction &I) {
1553 const Type *Ty = I.getOperand(0)->getType();
1554 switch (I.getOpcode()) {
1555 case Instruction::Add:
1556 case Instruction::Sub:
1557 case Instruction::Mul:
1558 // We need to cast integer arithmetic so that it is always performed
1559 // as unsigned, to avoid undefined behavior on overflow.
1560 case Instruction::LShr:
1561 case Instruction::URem:
1562 case Instruction::UDiv:
1564 printSimpleType(Out, Ty, false);
1567 case Instruction::AShr:
1568 case Instruction::SRem:
1569 case Instruction::SDiv:
1571 printSimpleType(Out, Ty, true);
1579 // Write the operand with a cast to another type based on the Opcode being used.
1580 // This will be used in cases where an instruction has specific type
1581 // requirements (usually signedness) for its operands.
1582 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1584 // Extract the operand's type, we'll need it.
1585 const Type* OpTy = Operand->getType();
1587 // Indicate whether to do the cast or not.
1588 bool shouldCast = false;
1590 // Indicate whether the cast should be to a signed type or not.
1591 bool castIsSigned = false;
1593 // Based on the Opcode for which this Operand is being written, determine
1594 // the new type to which the operand should be casted by setting the value
1595 // of OpTy. If we change OpTy, also set shouldCast to true.
1598 // for most instructions, it doesn't matter
1600 case Instruction::Add:
1601 case Instruction::Sub:
1602 case Instruction::Mul:
1603 // We need to cast integer arithmetic so that it is always performed
1604 // as unsigned, to avoid undefined behavior on overflow.
1605 case Instruction::LShr:
1606 case Instruction::UDiv:
1607 case Instruction::URem: // Cast to unsigned first
1609 castIsSigned = false;
1611 case Instruction::GetElementPtr:
1612 case Instruction::AShr:
1613 case Instruction::SDiv:
1614 case Instruction::SRem: // Cast to signed first
1616 castIsSigned = true;
1620 // Write out the casted operand if we should, otherwise just write the
1624 printSimpleType(Out, OpTy, castIsSigned);
1626 writeOperand(Operand);
1629 writeOperand(Operand);
1632 // Write the operand with a cast to another type based on the icmp predicate
1634 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1635 // This has to do a cast to ensure the operand has the right signedness.
1636 // Also, if the operand is a pointer, we make sure to cast to an integer when
1637 // doing the comparison both for signedness and so that the C compiler doesn't
1638 // optimize things like "p < NULL" to false (p may contain an integer value
1640 bool shouldCast = Cmp.isRelational();
1642 // Write out the casted operand if we should, otherwise just write the
1645 writeOperand(Operand);
1649 // Should this be a signed comparison? If so, convert to signed.
1650 bool castIsSigned = Cmp.isSigned();
1652 // If the operand was a pointer, convert to a large integer type.
1653 const Type* OpTy = Operand->getType();
1654 if (isa<PointerType>(OpTy))
1655 OpTy = TD->getIntPtrType(Operand->getContext());
1658 printSimpleType(Out, OpTy, castIsSigned);
1660 writeOperand(Operand);
1664 // generateCompilerSpecificCode - This is where we add conditional compilation
1665 // directives to cater to specific compilers as need be.
1667 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1668 const TargetData *TD) {
1669 // Alloca is hard to get, and we don't want to include stdlib.h here.
1670 Out << "/* get a declaration for alloca */\n"
1671 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1672 << "#define alloca(x) __builtin_alloca((x))\n"
1673 << "#define _alloca(x) __builtin_alloca((x))\n"
1674 << "#elif defined(__APPLE__)\n"
1675 << "extern void *__builtin_alloca(unsigned long);\n"
1676 << "#define alloca(x) __builtin_alloca(x)\n"
1677 << "#define longjmp _longjmp\n"
1678 << "#define setjmp _setjmp\n"
1679 << "#elif defined(__sun__)\n"
1680 << "#if defined(__sparcv9)\n"
1681 << "extern void *__builtin_alloca(unsigned long);\n"
1683 << "extern void *__builtin_alloca(unsigned int);\n"
1685 << "#define alloca(x) __builtin_alloca(x)\n"
1686 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1687 << "#define alloca(x) __builtin_alloca(x)\n"
1688 << "#elif defined(_MSC_VER)\n"
1689 << "#define inline _inline\n"
1690 << "#define alloca(x) _alloca(x)\n"
1692 << "#include <alloca.h>\n"
1695 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1696 // If we aren't being compiled with GCC, just drop these attributes.
1697 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1698 << "#define __attribute__(X)\n"
1701 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1702 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1703 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1704 << "#elif defined(__GNUC__)\n"
1705 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1707 << "#define __EXTERNAL_WEAK__\n"
1710 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1711 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1712 << "#define __ATTRIBUTE_WEAK__\n"
1713 << "#elif defined(__GNUC__)\n"
1714 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1716 << "#define __ATTRIBUTE_WEAK__\n"
1719 // Add hidden visibility support. FIXME: APPLE_CC?
1720 Out << "#if defined(__GNUC__)\n"
1721 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1724 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1725 // From the GCC documentation:
1727 // double __builtin_nan (const char *str)
1729 // This is an implementation of the ISO C99 function nan.
1731 // Since ISO C99 defines this function in terms of strtod, which we do
1732 // not implement, a description of the parsing is in order. The string is
1733 // parsed as by strtol; that is, the base is recognized by leading 0 or
1734 // 0x prefixes. The number parsed is placed in the significand such that
1735 // the least significant bit of the number is at the least significant
1736 // bit of the significand. The number is truncated to fit the significand
1737 // field provided. The significand is forced to be a quiet NaN.
1739 // This function, if given a string literal, is evaluated early enough
1740 // that it is considered a compile-time constant.
1742 // float __builtin_nanf (const char *str)
1744 // Similar to __builtin_nan, except the return type is float.
1746 // double __builtin_inf (void)
1748 // Similar to __builtin_huge_val, except a warning is generated if the
1749 // target floating-point format does not support infinities. This
1750 // function is suitable for implementing the ISO C99 macro INFINITY.
1752 // float __builtin_inff (void)
1754 // Similar to __builtin_inf, except the return type is float.
1755 Out << "#ifdef __GNUC__\n"
1756 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1757 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1758 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1759 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1760 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1761 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1762 << "#define LLVM_PREFETCH(addr,rw,locality) "
1763 "__builtin_prefetch(addr,rw,locality)\n"
1764 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1765 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1766 << "#define LLVM_ASM __asm__\n"
1768 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1769 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1770 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1771 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1772 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1773 << "#define LLVM_INFF 0.0F /* Float */\n"
1774 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1775 << "#define __ATTRIBUTE_CTOR__\n"
1776 << "#define __ATTRIBUTE_DTOR__\n"
1777 << "#define LLVM_ASM(X)\n"
1780 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1781 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1782 << "#define __builtin_stack_restore(X) /* noop */\n"
1785 // Output typedefs for 128-bit integers. If these are needed with a
1786 // 32-bit target or with a C compiler that doesn't support mode(TI),
1787 // more drastic measures will be needed.
1788 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1789 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1790 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1793 // Output target-specific code that should be inserted into main.
1794 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1797 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1798 /// the StaticTors set.
1799 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1800 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1801 if (!InitList) return;
1803 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1804 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1805 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1807 if (CS->getOperand(1)->isNullValue())
1808 return; // Found a null terminator, exit printing.
1809 Constant *FP = CS->getOperand(1);
1810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1812 FP = CE->getOperand(0);
1813 if (Function *F = dyn_cast<Function>(FP))
1814 StaticTors.insert(F);
1818 enum SpecialGlobalClass {
1820 GlobalCtors, GlobalDtors,
1824 /// getGlobalVariableClass - If this is a global that is specially recognized
1825 /// by LLVM, return a code that indicates how we should handle it.
1826 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1827 // If this is a global ctors/dtors list, handle it now.
1828 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1829 if (GV->getName() == "llvm.global_ctors")
1831 else if (GV->getName() == "llvm.global_dtors")
1835 // Otherwise, it it is other metadata, don't print it. This catches things
1836 // like debug information.
1837 if (GV->getSection() == "llvm.metadata")
1843 // PrintEscapedString - Print each character of the specified string, escaping
1844 // it if it is not printable or if it is an escape char.
1845 static void PrintEscapedString(const char *Str, unsigned Length,
1847 for (unsigned i = 0; i != Length; ++i) {
1848 unsigned char C = Str[i];
1849 if (isprint(C) && C != '\\' && C != '"')
1858 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1862 // PrintEscapedString - Print each character of the specified string, escaping
1863 // it if it is not printable or if it is an escape char.
1864 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1865 PrintEscapedString(Str.c_str(), Str.size(), Out);
1868 bool CWriter::doInitialization(Module &M) {
1869 FunctionPass::doInitialization(M);
1874 TD = new TargetData(&M);
1875 IL = new IntrinsicLowering(*TD);
1876 IL->AddPrototypes(M);
1879 std::string Triple = TheModule->getTargetTriple();
1881 Triple = llvm::sys::getHostTriple();
1884 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1885 TAsm = Match->createAsmInfo(Triple);
1887 TAsm = new CBEMCAsmInfo();
1888 Mang = new Mangler(*TAsm);
1890 // Keep track of which functions are static ctors/dtors so they can have
1891 // an attribute added to their prototypes.
1892 std::set<Function*> StaticCtors, StaticDtors;
1893 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1895 switch (getGlobalVariableClass(I)) {
1898 FindStaticTors(I, StaticCtors);
1901 FindStaticTors(I, StaticDtors);
1906 // get declaration for alloca
1907 Out << "/* Provide Declarations */\n";
1908 Out << "#include <stdarg.h>\n"; // Varargs support
1909 Out << "#include <setjmp.h>\n"; // Unwind support
1910 generateCompilerSpecificCode(Out, TD);
1912 // Provide a definition for `bool' if not compiling with a C++ compiler.
1914 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1916 << "\n\n/* Support for floating point constants */\n"
1917 << "typedef unsigned long long ConstantDoubleTy;\n"
1918 << "typedef unsigned int ConstantFloatTy;\n"
1919 << "typedef struct { unsigned long long f1; unsigned short f2; "
1920 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1921 // This is used for both kinds of 128-bit long double; meaning differs.
1922 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1923 " ConstantFP128Ty;\n"
1924 << "\n\n/* Global Declarations */\n";
1926 // First output all the declarations for the program, because C requires
1927 // Functions & globals to be declared before they are used.
1929 if (!M.getModuleInlineAsm().empty()) {
1930 Out << "/* Module asm statements */\n"
1933 // Split the string into lines, to make it easier to read the .ll file.
1934 std::string Asm = M.getModuleInlineAsm();
1936 size_t NewLine = Asm.find_first_of('\n', CurPos);
1937 while (NewLine != std::string::npos) {
1938 // We found a newline, print the portion of the asm string from the
1939 // last newline up to this newline.
1941 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1945 NewLine = Asm.find_first_of('\n', CurPos);
1948 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1950 << "/* End Module asm statements */\n";
1953 // Loop over the symbol table, emitting all named constants...
1954 printModuleTypes(M.getTypeSymbolTable());
1956 // Global variable declarations...
1957 if (!M.global_empty()) {
1958 Out << "\n/* External Global Variable Declarations */\n";
1959 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1962 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1963 I->hasCommonLinkage())
1965 else if (I->hasDLLImportLinkage())
1966 Out << "__declspec(dllimport) ";
1968 continue; // Internal Global
1970 // Thread Local Storage
1971 if (I->isThreadLocal())
1974 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1976 if (I->hasExternalWeakLinkage())
1977 Out << " __EXTERNAL_WEAK__";
1982 // Function declarations
1983 Out << "\n/* Function Declarations */\n";
1984 Out << "double fmod(double, double);\n"; // Support for FP rem
1985 Out << "float fmodf(float, float);\n";
1986 Out << "long double fmodl(long double, long double);\n";
1988 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1989 // Don't print declarations for intrinsic functions.
1990 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1991 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1992 if (I->hasExternalWeakLinkage())
1994 printFunctionSignature(I, true);
1995 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1996 Out << " __ATTRIBUTE_WEAK__";
1997 if (I->hasExternalWeakLinkage())
1998 Out << " __EXTERNAL_WEAK__";
1999 if (StaticCtors.count(I))
2000 Out << " __ATTRIBUTE_CTOR__";
2001 if (StaticDtors.count(I))
2002 Out << " __ATTRIBUTE_DTOR__";
2003 if (I->hasHiddenVisibility())
2004 Out << " __HIDDEN__";
2006 if (I->hasName() && I->getName()[0] == 1)
2007 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
2013 // Output the global variable declarations
2014 if (!M.global_empty()) {
2015 Out << "\n\n/* Global Variable Declarations */\n";
2016 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2018 if (!I->isDeclaration()) {
2019 // Ignore special globals, such as debug info.
2020 if (getGlobalVariableClass(I))
2023 if (I->hasLocalLinkage())
2028 // Thread Local Storage
2029 if (I->isThreadLocal())
2032 printType(Out, I->getType()->getElementType(), false,
2035 if (I->hasLinkOnceLinkage())
2036 Out << " __attribute__((common))";
2037 else if (I->hasCommonLinkage()) // FIXME is this right?
2038 Out << " __ATTRIBUTE_WEAK__";
2039 else if (I->hasWeakLinkage())
2040 Out << " __ATTRIBUTE_WEAK__";
2041 else if (I->hasExternalWeakLinkage())
2042 Out << " __EXTERNAL_WEAK__";
2043 if (I->hasHiddenVisibility())
2044 Out << " __HIDDEN__";
2049 // Output the global variable definitions and contents...
2050 if (!M.global_empty()) {
2051 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
2052 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2054 if (!I->isDeclaration()) {
2055 // Ignore special globals, such as debug info.
2056 if (getGlobalVariableClass(I))
2059 if (I->hasLocalLinkage())
2061 else if (I->hasDLLImportLinkage())
2062 Out << "__declspec(dllimport) ";
2063 else if (I->hasDLLExportLinkage())
2064 Out << "__declspec(dllexport) ";
2066 // Thread Local Storage
2067 if (I->isThreadLocal())
2070 printType(Out, I->getType()->getElementType(), false,
2072 if (I->hasLinkOnceLinkage())
2073 Out << " __attribute__((common))";
2074 else if (I->hasWeakLinkage())
2075 Out << " __ATTRIBUTE_WEAK__";
2076 else if (I->hasCommonLinkage())
2077 Out << " __ATTRIBUTE_WEAK__";
2079 if (I->hasHiddenVisibility())
2080 Out << " __HIDDEN__";
2082 // If the initializer is not null, emit the initializer. If it is null,
2083 // we try to avoid emitting large amounts of zeros. The problem with
2084 // this, however, occurs when the variable has weak linkage. In this
2085 // case, the assembler will complain about the variable being both weak
2086 // and common, so we disable this optimization.
2087 // FIXME common linkage should avoid this problem.
2088 if (!I->getInitializer()->isNullValue()) {
2090 writeOperand(I->getInitializer(), true);
2091 } else if (I->hasWeakLinkage()) {
2092 // We have to specify an initializer, but it doesn't have to be
2093 // complete. If the value is an aggregate, print out { 0 }, and let
2094 // the compiler figure out the rest of the zeros.
2096 if (isa<StructType>(I->getInitializer()->getType()) ||
2097 isa<VectorType>(I->getInitializer()->getType())) {
2099 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2100 // As with structs and vectors, but with an extra set of braces
2101 // because arrays are wrapped in structs.
2104 // Just print it out normally.
2105 writeOperand(I->getInitializer(), true);
2113 Out << "\n\n/* Function Bodies */\n";
2115 // Emit some helper functions for dealing with FCMP instruction's
2117 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2118 Out << "return X == X && Y == Y; }\n";
2119 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2120 Out << "return X != X || Y != Y; }\n";
2121 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2122 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2123 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2124 Out << "return X != Y; }\n";
2125 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2126 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2127 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2128 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2129 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2130 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2131 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2132 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2133 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2134 Out << "return X == Y ; }\n";
2135 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2136 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2137 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2138 Out << "return X < Y ; }\n";
2139 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2140 Out << "return X > Y ; }\n";
2141 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2142 Out << "return X <= Y ; }\n";
2143 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2144 Out << "return X >= Y ; }\n";
2149 /// Output all floating point constants that cannot be printed accurately...
2150 void CWriter::printFloatingPointConstants(Function &F) {
2151 // Scan the module for floating point constants. If any FP constant is used
2152 // in the function, we want to redirect it here so that we do not depend on
2153 // the precision of the printed form, unless the printed form preserves
2156 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2158 printFloatingPointConstants(*I);
2163 void CWriter::printFloatingPointConstants(const Constant *C) {
2164 // If this is a constant expression, recursively check for constant fp values.
2165 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2166 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2167 printFloatingPointConstants(CE->getOperand(i));
2171 // Otherwise, check for a FP constant that we need to print.
2172 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2174 // Do not put in FPConstantMap if safe.
2175 isFPCSafeToPrint(FPC) ||
2176 // Already printed this constant?
2177 FPConstantMap.count(FPC))
2180 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2182 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2183 double Val = FPC->getValueAPF().convertToDouble();
2184 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2185 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2186 << " = 0x" << utohexstr(i)
2187 << "ULL; /* " << Val << " */\n";
2188 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2189 float Val = FPC->getValueAPF().convertToFloat();
2190 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2192 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2193 << " = 0x" << utohexstr(i)
2194 << "U; /* " << Val << " */\n";
2195 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2196 // api needed to prevent premature destruction
2197 APInt api = FPC->getValueAPF().bitcastToAPInt();
2198 const uint64_t *p = api.getRawData();
2199 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2200 << " = { 0x" << utohexstr(p[0])
2201 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2202 << "}; /* Long double constant */\n";
2203 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2204 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2205 APInt api = FPC->getValueAPF().bitcastToAPInt();
2206 const uint64_t *p = api.getRawData();
2207 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2209 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2210 << "}; /* Long double constant */\n";
2213 llvm_unreachable("Unknown float type!");
2219 /// printSymbolTable - Run through symbol table looking for type names. If a
2220 /// type name is found, emit its declaration...
2222 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2223 Out << "/* Helper union for bitcasts */\n";
2224 Out << "typedef union {\n";
2225 Out << " unsigned int Int32;\n";
2226 Out << " unsigned long long Int64;\n";
2227 Out << " float Float;\n";
2228 Out << " double Double;\n";
2229 Out << "} llvmBitCastUnion;\n";
2231 // We are only interested in the type plane of the symbol table.
2232 TypeSymbolTable::const_iterator I = TST.begin();
2233 TypeSymbolTable::const_iterator End = TST.end();
2235 // If there are no type names, exit early.
2236 if (I == End) return;
2238 // Print out forward declarations for structure types before anything else!
2239 Out << "/* Structure forward decls */\n";
2240 for (; I != End; ++I) {
2241 std::string Name = "struct " + Mangle("l_"+I->first);
2242 Out << Name << ";\n";
2243 TypeNames.insert(std::make_pair(I->second, Name));
2248 // Now we can print out typedefs. Above, we guaranteed that this can only be
2249 // for struct or opaque types.
2250 Out << "/* Typedefs */\n";
2251 for (I = TST.begin(); I != End; ++I) {
2252 std::string Name = Mangle("l_"+I->first);
2254 printType(Out, I->second, false, Name);
2260 // Keep track of which structures have been printed so far...
2261 std::set<const Type *> StructPrinted;
2263 // Loop over all structures then push them into the stack so they are
2264 // printed in the correct order.
2266 Out << "/* Structure contents */\n";
2267 for (I = TST.begin(); I != End; ++I)
2268 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2269 // Only print out used types!
2270 printContainedStructs(I->second, StructPrinted);
2273 // Push the struct onto the stack and recursively push all structs
2274 // this one depends on.
2276 // TODO: Make this work properly with vector types
2278 void CWriter::printContainedStructs(const Type *Ty,
2279 std::set<const Type*> &StructPrinted) {
2280 // Don't walk through pointers.
2281 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2283 // Print all contained types first.
2284 for (Type::subtype_iterator I = Ty->subtype_begin(),
2285 E = Ty->subtype_end(); I != E; ++I)
2286 printContainedStructs(*I, StructPrinted);
2288 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2289 // Check to see if we have already printed this struct.
2290 if (StructPrinted.insert(Ty).second) {
2291 // Print structure type out.
2292 std::string Name = TypeNames[Ty];
2293 printType(Out, Ty, false, Name, true);
2299 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2300 /// isStructReturn - Should this function actually return a struct by-value?
2301 bool isStructReturn = F->hasStructRetAttr();
2303 if (F->hasLocalLinkage()) Out << "static ";
2304 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2305 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2306 switch (F->getCallingConv()) {
2307 case CallingConv::X86_StdCall:
2308 Out << "__attribute__((stdcall)) ";
2310 case CallingConv::X86_FastCall:
2311 Out << "__attribute__((fastcall)) ";
2317 // Loop over the arguments, printing them...
2318 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2319 const AttrListPtr &PAL = F->getAttributes();
2321 std::stringstream FunctionInnards;
2323 // Print out the name...
2324 FunctionInnards << GetValueName(F) << '(';
2326 bool PrintedArg = false;
2327 if (!F->isDeclaration()) {
2328 if (!F->arg_empty()) {
2329 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2332 // If this is a struct-return function, don't print the hidden
2333 // struct-return argument.
2334 if (isStructReturn) {
2335 assert(I != E && "Invalid struct return function!");
2340 std::string ArgName;
2341 for (; I != E; ++I) {
2342 if (PrintedArg) FunctionInnards << ", ";
2343 if (I->hasName() || !Prototype)
2344 ArgName = GetValueName(I);
2347 const Type *ArgTy = I->getType();
2348 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2349 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2350 ByValParams.insert(I);
2352 printType(FunctionInnards, ArgTy,
2353 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2360 // Loop over the arguments, printing them.
2361 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2364 // If this is a struct-return function, don't print the hidden
2365 // struct-return argument.
2366 if (isStructReturn) {
2367 assert(I != E && "Invalid struct return function!");
2372 for (; I != E; ++I) {
2373 if (PrintedArg) FunctionInnards << ", ";
2374 const Type *ArgTy = *I;
2375 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2376 assert(isa<PointerType>(ArgTy));
2377 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2379 printType(FunctionInnards, ArgTy,
2380 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2386 // Finish printing arguments... if this is a vararg function, print the ...,
2387 // unless there are no known types, in which case, we just emit ().
2389 if (FT->isVarArg() && PrintedArg) {
2390 if (PrintedArg) FunctionInnards << ", ";
2391 FunctionInnards << "..."; // Output varargs portion of signature!
2392 } else if (!FT->isVarArg() && !PrintedArg) {
2393 FunctionInnards << "void"; // ret() -> ret(void) in C.
2395 FunctionInnards << ')';
2397 // Get the return tpe for the function.
2399 if (!isStructReturn)
2400 RetTy = F->getReturnType();
2402 // If this is a struct-return function, print the struct-return type.
2403 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2406 // Print out the return type and the signature built above.
2407 printType(Out, RetTy,
2408 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2409 FunctionInnards.str());
2412 static inline bool isFPIntBitCast(const Instruction &I) {
2413 if (!isa<BitCastInst>(I))
2415 const Type *SrcTy = I.getOperand(0)->getType();
2416 const Type *DstTy = I.getType();
2417 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2418 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2421 void CWriter::printFunction(Function &F) {
2422 /// isStructReturn - Should this function actually return a struct by-value?
2423 bool isStructReturn = F.hasStructRetAttr();
2425 printFunctionSignature(&F, false);
2428 // If this is a struct return function, handle the result with magic.
2429 if (isStructReturn) {
2430 const Type *StructTy =
2431 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2433 printType(Out, StructTy, false, "StructReturn");
2434 Out << "; /* Struct return temporary */\n";
2437 printType(Out, F.arg_begin()->getType(), false,
2438 GetValueName(F.arg_begin()));
2439 Out << " = &StructReturn;\n";
2442 bool PrintedVar = false;
2444 // print local variable information for the function
2445 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2446 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2448 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2449 Out << "; /* Address-exposed local */\n";
2451 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2452 !isInlinableInst(*I)) {
2454 printType(Out, I->getType(), false, GetValueName(&*I));
2457 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2459 printType(Out, I->getType(), false,
2460 GetValueName(&*I)+"__PHI_TEMPORARY");
2465 // We need a temporary for the BitCast to use so it can pluck a value out
2466 // of a union to do the BitCast. This is separate from the need for a
2467 // variable to hold the result of the BitCast.
2468 if (isFPIntBitCast(*I)) {
2469 Out << " llvmBitCastUnion " << GetValueName(&*I)
2470 << "__BITCAST_TEMPORARY;\n";
2478 if (F.hasExternalLinkage() && F.getName() == "main")
2479 Out << " CODE_FOR_MAIN();\n";
2481 // print the basic blocks
2482 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2483 if (Loop *L = LI->getLoopFor(BB)) {
2484 if (L->getHeader() == BB && L->getParentLoop() == 0)
2487 printBasicBlock(BB);
2494 void CWriter::printLoop(Loop *L) {
2495 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2496 << "' to make GCC happy */\n";
2497 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2498 BasicBlock *BB = L->getBlocks()[i];
2499 Loop *BBLoop = LI->getLoopFor(BB);
2501 printBasicBlock(BB);
2502 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2505 Out << " } while (1); /* end of syntactic loop '"
2506 << L->getHeader()->getName() << "' */\n";
2509 void CWriter::printBasicBlock(BasicBlock *BB) {
2511 // Don't print the label for the basic block if there are no uses, or if
2512 // the only terminator use is the predecessor basic block's terminator.
2513 // We have to scan the use list because PHI nodes use basic blocks too but
2514 // do not require a label to be generated.
2516 bool NeedsLabel = false;
2517 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2518 if (isGotoCodeNecessary(*PI, BB)) {
2523 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2525 // Output all of the instructions in the basic block...
2526 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2528 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2529 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2534 writeInstComputationInline(*II);
2539 // Don't emit prefix or suffix for the terminator.
2540 visit(*BB->getTerminator());
2544 // Specific Instruction type classes... note that all of the casts are
2545 // necessary because we use the instruction classes as opaque types...
2547 void CWriter::visitReturnInst(ReturnInst &I) {
2548 // If this is a struct return function, return the temporary struct.
2549 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2551 if (isStructReturn) {
2552 Out << " return StructReturn;\n";
2556 // Don't output a void return if this is the last basic block in the function
2557 if (I.getNumOperands() == 0 &&
2558 &*--I.getParent()->getParent()->end() == I.getParent() &&
2559 !I.getParent()->size() == 1) {
2563 if (I.getNumOperands() > 1) {
2566 printType(Out, I.getParent()->getParent()->getReturnType());
2567 Out << " llvm_cbe_mrv_temp = {\n";
2568 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2570 writeOperand(I.getOperand(i));
2576 Out << " return llvm_cbe_mrv_temp;\n";
2582 if (I.getNumOperands()) {
2584 writeOperand(I.getOperand(0));
2589 void CWriter::visitSwitchInst(SwitchInst &SI) {
2592 writeOperand(SI.getOperand(0));
2593 Out << ") {\n default:\n";
2594 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2595 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2597 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2599 writeOperand(SI.getOperand(i));
2601 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2602 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2603 printBranchToBlock(SI.getParent(), Succ, 2);
2604 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2610 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2611 Out << " goto *(void*)(";
2612 writeOperand(IBI.getOperand(0));
2616 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2617 Out << " /*UNREACHABLE*/;\n";
2620 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2621 /// FIXME: This should be reenabled, but loop reordering safe!!
2624 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2625 return true; // Not the direct successor, we need a goto.
2627 //isa<SwitchInst>(From->getTerminator())
2629 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2634 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2635 BasicBlock *Successor,
2637 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2638 PHINode *PN = cast<PHINode>(I);
2639 // Now we have to do the printing.
2640 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2641 if (!isa<UndefValue>(IV)) {
2642 Out << std::string(Indent, ' ');
2643 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2645 Out << "; /* for PHI node */\n";
2650 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2652 if (isGotoCodeNecessary(CurBB, Succ)) {
2653 Out << std::string(Indent, ' ') << " goto ";
2659 // Branch instruction printing - Avoid printing out a branch to a basic block
2660 // that immediately succeeds the current one.
2662 void CWriter::visitBranchInst(BranchInst &I) {
2664 if (I.isConditional()) {
2665 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2667 writeOperand(I.getCondition());
2670 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2671 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2673 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2674 Out << " } else {\n";
2675 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2676 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2679 // First goto not necessary, assume second one is...
2681 writeOperand(I.getCondition());
2684 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2685 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2690 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2691 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2696 // PHI nodes get copied into temporary values at the end of predecessor basic
2697 // blocks. We now need to copy these temporary values into the REAL value for
2699 void CWriter::visitPHINode(PHINode &I) {
2701 Out << "__PHI_TEMPORARY";
2705 void CWriter::visitBinaryOperator(Instruction &I) {
2706 // binary instructions, shift instructions, setCond instructions.
2707 assert(!isa<PointerType>(I.getType()));
2709 // We must cast the results of binary operations which might be promoted.
2710 bool needsCast = false;
2711 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2712 (I.getType() == Type::getInt16Ty(I.getContext()))
2713 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2716 printType(Out, I.getType(), false);
2720 // If this is a negation operation, print it out as such. For FP, we don't
2721 // want to print "-0.0 - X".
2722 if (BinaryOperator::isNeg(&I)) {
2724 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2726 } else if (BinaryOperator::isFNeg(&I)) {
2728 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2730 } else if (I.getOpcode() == Instruction::FRem) {
2731 // Output a call to fmod/fmodf instead of emitting a%b
2732 if (I.getType() == Type::getFloatTy(I.getContext()))
2734 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2736 else // all 3 flavors of long double
2738 writeOperand(I.getOperand(0));
2740 writeOperand(I.getOperand(1));
2744 // Write out the cast of the instruction's value back to the proper type
2746 bool NeedsClosingParens = writeInstructionCast(I);
2748 // Certain instructions require the operand to be forced to a specific type
2749 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2750 // below for operand 1
2751 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2753 switch (I.getOpcode()) {
2754 case Instruction::Add:
2755 case Instruction::FAdd: Out << " + "; break;
2756 case Instruction::Sub:
2757 case Instruction::FSub: Out << " - "; break;
2758 case Instruction::Mul:
2759 case Instruction::FMul: Out << " * "; break;
2760 case Instruction::URem:
2761 case Instruction::SRem:
2762 case Instruction::FRem: Out << " % "; break;
2763 case Instruction::UDiv:
2764 case Instruction::SDiv:
2765 case Instruction::FDiv: Out << " / "; break;
2766 case Instruction::And: Out << " & "; break;
2767 case Instruction::Or: Out << " | "; break;
2768 case Instruction::Xor: Out << " ^ "; break;
2769 case Instruction::Shl : Out << " << "; break;
2770 case Instruction::LShr:
2771 case Instruction::AShr: Out << " >> "; break;
2774 errs() << "Invalid operator type!" << I;
2776 llvm_unreachable(0);
2779 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2780 if (NeedsClosingParens)
2789 void CWriter::visitICmpInst(ICmpInst &I) {
2790 // We must cast the results of icmp which might be promoted.
2791 bool needsCast = false;
2793 // Write out the cast of the instruction's value back to the proper type
2795 bool NeedsClosingParens = writeInstructionCast(I);
2797 // Certain icmp predicate require the operand to be forced to a specific type
2798 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2799 // below for operand 1
2800 writeOperandWithCast(I.getOperand(0), I);
2802 switch (I.getPredicate()) {
2803 case ICmpInst::ICMP_EQ: Out << " == "; break;
2804 case ICmpInst::ICMP_NE: Out << " != "; break;
2805 case ICmpInst::ICMP_ULE:
2806 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2807 case ICmpInst::ICMP_UGE:
2808 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2809 case ICmpInst::ICMP_ULT:
2810 case ICmpInst::ICMP_SLT: Out << " < "; break;
2811 case ICmpInst::ICMP_UGT:
2812 case ICmpInst::ICMP_SGT: Out << " > "; break;
2815 errs() << "Invalid icmp predicate!" << I;
2817 llvm_unreachable(0);
2820 writeOperandWithCast(I.getOperand(1), I);
2821 if (NeedsClosingParens)
2829 void CWriter::visitFCmpInst(FCmpInst &I) {
2830 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2834 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2840 switch (I.getPredicate()) {
2841 default: llvm_unreachable("Illegal FCmp predicate");
2842 case FCmpInst::FCMP_ORD: op = "ord"; break;
2843 case FCmpInst::FCMP_UNO: op = "uno"; break;
2844 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2845 case FCmpInst::FCMP_UNE: op = "une"; break;
2846 case FCmpInst::FCMP_ULT: op = "ult"; break;
2847 case FCmpInst::FCMP_ULE: op = "ule"; break;
2848 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2849 case FCmpInst::FCMP_UGE: op = "uge"; break;
2850 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2851 case FCmpInst::FCMP_ONE: op = "one"; break;
2852 case FCmpInst::FCMP_OLT: op = "olt"; break;
2853 case FCmpInst::FCMP_OLE: op = "ole"; break;
2854 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2855 case FCmpInst::FCMP_OGE: op = "oge"; break;
2858 Out << "llvm_fcmp_" << op << "(";
2859 // Write the first operand
2860 writeOperand(I.getOperand(0));
2862 // Write the second operand
2863 writeOperand(I.getOperand(1));
2867 static const char * getFloatBitCastField(const Type *Ty) {
2868 switch (Ty->getTypeID()) {
2869 default: llvm_unreachable("Invalid Type");
2870 case Type::FloatTyID: return "Float";
2871 case Type::DoubleTyID: return "Double";
2872 case Type::IntegerTyID: {
2873 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2882 void CWriter::visitCastInst(CastInst &I) {
2883 const Type *DstTy = I.getType();
2884 const Type *SrcTy = I.getOperand(0)->getType();
2885 if (isFPIntBitCast(I)) {
2887 // These int<->float and long<->double casts need to be handled specially
2888 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2889 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2890 writeOperand(I.getOperand(0));
2891 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2892 << getFloatBitCastField(I.getType());
2898 printCast(I.getOpcode(), SrcTy, DstTy);
2900 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2901 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2902 I.getOpcode() == Instruction::SExt)
2905 writeOperand(I.getOperand(0));
2907 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2908 (I.getOpcode() == Instruction::Trunc ||
2909 I.getOpcode() == Instruction::FPToUI ||
2910 I.getOpcode() == Instruction::FPToSI ||
2911 I.getOpcode() == Instruction::PtrToInt)) {
2912 // Make sure we really get a trunc to bool by anding the operand with 1
2918 void CWriter::visitSelectInst(SelectInst &I) {
2920 writeOperand(I.getCondition());
2922 writeOperand(I.getTrueValue());
2924 writeOperand(I.getFalseValue());
2929 void CWriter::lowerIntrinsics(Function &F) {
2930 // This is used to keep track of intrinsics that get generated to a lowered
2931 // function. We must generate the prototypes before the function body which
2932 // will only be expanded on first use (by the loop below).
2933 std::vector<Function*> prototypesToGen;
2935 // Examine all the instructions in this function to find the intrinsics that
2936 // need to be lowered.
2937 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2938 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2939 if (CallInst *CI = dyn_cast<CallInst>(I++))
2940 if (Function *F = CI->getCalledFunction())
2941 switch (F->getIntrinsicID()) {
2942 case Intrinsic::not_intrinsic:
2943 case Intrinsic::memory_barrier:
2944 case Intrinsic::vastart:
2945 case Intrinsic::vacopy:
2946 case Intrinsic::vaend:
2947 case Intrinsic::returnaddress:
2948 case Intrinsic::frameaddress:
2949 case Intrinsic::setjmp:
2950 case Intrinsic::longjmp:
2951 case Intrinsic::prefetch:
2952 case Intrinsic::powi:
2953 case Intrinsic::x86_sse_cmp_ss:
2954 case Intrinsic::x86_sse_cmp_ps:
2955 case Intrinsic::x86_sse2_cmp_sd:
2956 case Intrinsic::x86_sse2_cmp_pd:
2957 case Intrinsic::ppc_altivec_lvsl:
2958 // We directly implement these intrinsics
2961 // If this is an intrinsic that directly corresponds to a GCC
2962 // builtin, we handle it.
2963 const char *BuiltinName = "";
2964 #define GET_GCC_BUILTIN_NAME
2965 #include "llvm/Intrinsics.gen"
2966 #undef GET_GCC_BUILTIN_NAME
2967 // If we handle it, don't lower it.
2968 if (BuiltinName[0]) break;
2970 // All other intrinsic calls we must lower.
2971 Instruction *Before = 0;
2972 if (CI != &BB->front())
2973 Before = prior(BasicBlock::iterator(CI));
2975 IL->LowerIntrinsicCall(CI);
2976 if (Before) { // Move iterator to instruction after call
2981 // If the intrinsic got lowered to another call, and that call has
2982 // a definition then we need to make sure its prototype is emitted
2983 // before any calls to it.
2984 if (CallInst *Call = dyn_cast<CallInst>(I))
2985 if (Function *NewF = Call->getCalledFunction())
2986 if (!NewF->isDeclaration())
2987 prototypesToGen.push_back(NewF);
2992 // We may have collected some prototypes to emit in the loop above.
2993 // Emit them now, before the function that uses them is emitted. But,
2994 // be careful not to emit them twice.
2995 std::vector<Function*>::iterator I = prototypesToGen.begin();
2996 std::vector<Function*>::iterator E = prototypesToGen.end();
2997 for ( ; I != E; ++I) {
2998 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
3000 printFunctionSignature(*I, true);
3006 void CWriter::visitCallInst(CallInst &I) {
3007 if (isa<InlineAsm>(I.getOperand(0)))
3008 return visitInlineAsm(I);
3010 bool WroteCallee = false;
3012 // Handle intrinsic function calls first...
3013 if (Function *F = I.getCalledFunction())
3014 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3015 if (visitBuiltinCall(I, ID, WroteCallee))
3018 Value *Callee = I.getCalledValue();
3020 const PointerType *PTy = cast<PointerType>(Callee->getType());
3021 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3023 // If this is a call to a struct-return function, assign to the first
3024 // parameter instead of passing it to the call.
3025 const AttrListPtr &PAL = I.getAttributes();
3026 bool hasByVal = I.hasByValArgument();
3027 bool isStructRet = I.hasStructRetAttr();
3029 writeOperandDeref(I.getOperand(1));
3033 if (I.isTailCall()) Out << " /*tail*/ ";
3036 // If this is an indirect call to a struct return function, we need to cast
3037 // the pointer. Ditto for indirect calls with byval arguments.
3038 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
3040 // GCC is a real PITA. It does not permit codegening casts of functions to
3041 // function pointers if they are in a call (it generates a trap instruction
3042 // instead!). We work around this by inserting a cast to void* in between
3043 // the function and the function pointer cast. Unfortunately, we can't just
3044 // form the constant expression here, because the folder will immediately
3047 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3048 // that void* and function pointers have the same size. :( To deal with this
3049 // in the common case, we handle casts where the number of arguments passed
3052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3054 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3060 // Ok, just cast the pointer type.
3063 printStructReturnPointerFunctionType(Out, PAL,
3064 cast<PointerType>(I.getCalledValue()->getType()));
3066 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3068 printType(Out, I.getCalledValue()->getType());
3071 writeOperand(Callee);
3072 if (NeedsCast) Out << ')';
3077 unsigned NumDeclaredParams = FTy->getNumParams();
3079 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3081 if (isStructRet) { // Skip struct return argument.
3086 bool PrintedArg = false;
3087 for (; AI != AE; ++AI, ++ArgNo) {
3088 if (PrintedArg) Out << ", ";
3089 if (ArgNo < NumDeclaredParams &&
3090 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3092 printType(Out, FTy->getParamType(ArgNo),
3093 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3096 // Check if the argument is expected to be passed by value.
3097 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3098 writeOperandDeref(*AI);
3106 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3107 /// if the entire call is handled, return false it it wasn't handled, and
3108 /// optionally set 'WroteCallee' if the callee has already been printed out.
3109 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3110 bool &WroteCallee) {
3113 // If this is an intrinsic that directly corresponds to a GCC
3114 // builtin, we emit it here.
3115 const char *BuiltinName = "";
3116 Function *F = I.getCalledFunction();
3117 #define GET_GCC_BUILTIN_NAME
3118 #include "llvm/Intrinsics.gen"
3119 #undef GET_GCC_BUILTIN_NAME
3120 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3126 case Intrinsic::memory_barrier:
3127 Out << "__sync_synchronize()";
3129 case Intrinsic::vastart:
3132 Out << "va_start(*(va_list*)";
3133 writeOperand(I.getOperand(1));
3135 // Output the last argument to the enclosing function.
3136 if (I.getParent()->getParent()->arg_empty()) {
3138 raw_string_ostream Msg(msg);
3139 Msg << "The C backend does not currently support zero "
3140 << "argument varargs functions, such as '"
3141 << I.getParent()->getParent()->getName() << "'!";
3142 llvm_report_error(Msg.str());
3144 writeOperand(--I.getParent()->getParent()->arg_end());
3147 case Intrinsic::vaend:
3148 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3149 Out << "0; va_end(*(va_list*)";
3150 writeOperand(I.getOperand(1));
3153 Out << "va_end(*(va_list*)0)";
3156 case Intrinsic::vacopy:
3158 Out << "va_copy(*(va_list*)";
3159 writeOperand(I.getOperand(1));
3160 Out << ", *(va_list*)";
3161 writeOperand(I.getOperand(2));
3164 case Intrinsic::returnaddress:
3165 Out << "__builtin_return_address(";
3166 writeOperand(I.getOperand(1));
3169 case Intrinsic::frameaddress:
3170 Out << "__builtin_frame_address(";
3171 writeOperand(I.getOperand(1));
3174 case Intrinsic::powi:
3175 Out << "__builtin_powi(";
3176 writeOperand(I.getOperand(1));
3178 writeOperand(I.getOperand(2));
3181 case Intrinsic::setjmp:
3182 Out << "setjmp(*(jmp_buf*)";
3183 writeOperand(I.getOperand(1));
3186 case Intrinsic::longjmp:
3187 Out << "longjmp(*(jmp_buf*)";
3188 writeOperand(I.getOperand(1));
3190 writeOperand(I.getOperand(2));
3193 case Intrinsic::prefetch:
3194 Out << "LLVM_PREFETCH((const void *)";
3195 writeOperand(I.getOperand(1));
3197 writeOperand(I.getOperand(2));
3199 writeOperand(I.getOperand(3));
3202 case Intrinsic::stacksave:
3203 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3204 // to work around GCC bugs (see PR1809).
3205 Out << "0; *((void**)&" << GetValueName(&I)
3206 << ") = __builtin_stack_save()";
3208 case Intrinsic::x86_sse_cmp_ss:
3209 case Intrinsic::x86_sse_cmp_ps:
3210 case Intrinsic::x86_sse2_cmp_sd:
3211 case Intrinsic::x86_sse2_cmp_pd:
3213 printType(Out, I.getType());
3215 // Multiple GCC builtins multiplex onto this intrinsic.
3216 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3217 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3218 case 0: Out << "__builtin_ia32_cmpeq"; break;
3219 case 1: Out << "__builtin_ia32_cmplt"; break;
3220 case 2: Out << "__builtin_ia32_cmple"; break;
3221 case 3: Out << "__builtin_ia32_cmpunord"; break;
3222 case 4: Out << "__builtin_ia32_cmpneq"; break;
3223 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3224 case 6: Out << "__builtin_ia32_cmpnle"; break;
3225 case 7: Out << "__builtin_ia32_cmpord"; break;
3227 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3231 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3237 writeOperand(I.getOperand(1));
3239 writeOperand(I.getOperand(2));
3242 case Intrinsic::ppc_altivec_lvsl:
3244 printType(Out, I.getType());
3246 Out << "__builtin_altivec_lvsl(0, (void*)";
3247 writeOperand(I.getOperand(1));
3253 //This converts the llvm constraint string to something gcc is expecting.
3254 //TODO: work out platform independent constraints and factor those out
3255 // of the per target tables
3256 // handle multiple constraint codes
3257 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3258 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3260 // Grab the translation table from MCAsmInfo if it exists.
3261 const MCAsmInfo *TargetAsm;
3262 std::string Triple = TheModule->getTargetTriple();
3264 Triple = llvm::sys::getHostTriple();
3267 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3268 TargetAsm = Match->createAsmInfo(Triple);
3272 const char *const *table = TargetAsm->getAsmCBE();
3274 // Search the translation table if it exists.
3275 for (int i = 0; table && table[i]; i += 2)
3276 if (c.Codes[0] == table[i]) {
3281 // Default is identity.
3286 //TODO: import logic from AsmPrinter.cpp
3287 static std::string gccifyAsm(std::string asmstr) {
3288 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3289 if (asmstr[i] == '\n')
3290 asmstr.replace(i, 1, "\\n");
3291 else if (asmstr[i] == '\t')
3292 asmstr.replace(i, 1, "\\t");
3293 else if (asmstr[i] == '$') {
3294 if (asmstr[i + 1] == '{') {
3295 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3296 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3297 std::string n = "%" +
3298 asmstr.substr(a + 1, b - a - 1) +
3299 asmstr.substr(i + 2, a - i - 2);
3300 asmstr.replace(i, b - i + 1, n);
3303 asmstr.replace(i, 1, "%");
3305 else if (asmstr[i] == '%')//grr
3306 { asmstr.replace(i, 1, "%%"); ++i;}
3311 //TODO: assumptions about what consume arguments from the call are likely wrong
3312 // handle communitivity
3313 void CWriter::visitInlineAsm(CallInst &CI) {
3314 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3315 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3317 std::vector<std::pair<Value*, int> > ResultVals;
3318 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3320 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3321 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3322 ResultVals.push_back(std::make_pair(&CI, (int)i));
3324 ResultVals.push_back(std::make_pair(&CI, -1));
3327 // Fix up the asm string for gcc and emit it.
3328 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3331 unsigned ValueCount = 0;
3332 bool IsFirst = true;
3334 // Convert over all the output constraints.
3335 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3336 E = Constraints.end(); I != E; ++I) {
3338 if (I->Type != InlineAsm::isOutput) {
3340 continue; // Ignore non-output constraints.
3343 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3344 std::string C = InterpretASMConstraint(*I);
3345 if (C.empty()) continue;
3356 if (ValueCount < ResultVals.size()) {
3357 DestVal = ResultVals[ValueCount].first;
3358 DestValNo = ResultVals[ValueCount].second;
3360 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3362 if (I->isEarlyClobber)
3365 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3366 if (DestValNo != -1)
3367 Out << ".field" << DestValNo; // Multiple retvals.
3373 // Convert over all the input constraints.
3377 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3378 E = Constraints.end(); I != E; ++I) {
3379 if (I->Type != InlineAsm::isInput) {
3381 continue; // Ignore non-input constraints.
3384 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3385 std::string C = InterpretASMConstraint(*I);
3386 if (C.empty()) continue;
3393 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3394 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3396 Out << "\"" << C << "\"(";
3398 writeOperand(SrcVal);
3400 writeOperandDeref(SrcVal);
3404 // Convert over the clobber constraints.
3406 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3407 E = Constraints.end(); I != E; ++I) {
3408 if (I->Type != InlineAsm::isClobber)
3409 continue; // Ignore non-input constraints.
3411 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3412 std::string C = InterpretASMConstraint(*I);
3413 if (C.empty()) continue;
3420 Out << '\"' << C << '"';
3426 void CWriter::visitAllocaInst(AllocaInst &I) {
3428 printType(Out, I.getType());
3429 Out << ") alloca(sizeof(";
3430 printType(Out, I.getType()->getElementType());
3432 if (I.isArrayAllocation()) {
3434 writeOperand(I.getOperand(0));
3439 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3440 gep_type_iterator E, bool Static) {
3442 // If there are no indices, just print out the pointer.
3448 // Find out if the last index is into a vector. If so, we have to print this
3449 // specially. Since vectors can't have elements of indexable type, only the
3450 // last index could possibly be of a vector element.
3451 const VectorType *LastIndexIsVector = 0;
3453 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3454 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3459 // If the last index is into a vector, we can't print it as &a[i][j] because
3460 // we can't index into a vector with j in GCC. Instead, emit this as
3461 // (((float*)&a[i])+j)
3462 if (LastIndexIsVector) {
3464 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3470 // If the first index is 0 (very typical) we can do a number of
3471 // simplifications to clean up the code.
3472 Value *FirstOp = I.getOperand();
3473 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3474 // First index isn't simple, print it the hard way.
3477 ++I; // Skip the zero index.
3479 // Okay, emit the first operand. If Ptr is something that is already address
3480 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3481 if (isAddressExposed(Ptr)) {
3482 writeOperandInternal(Ptr, Static);
3483 } else if (I != E && isa<StructType>(*I)) {
3484 // If we didn't already emit the first operand, see if we can print it as
3485 // P->f instead of "P[0].f"
3487 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3488 ++I; // eat the struct index as well.
3490 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3497 for (; I != E; ++I) {
3498 if (isa<StructType>(*I)) {
3499 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3500 } else if (isa<ArrayType>(*I)) {
3502 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3504 } else if (!isa<VectorType>(*I)) {
3506 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3509 // If the last index is into a vector, then print it out as "+j)". This
3510 // works with the 'LastIndexIsVector' code above.
3511 if (isa<Constant>(I.getOperand()) &&
3512 cast<Constant>(I.getOperand())->isNullValue()) {
3513 Out << "))"; // avoid "+0".
3516 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3524 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3525 bool IsVolatile, unsigned Alignment) {
3527 bool IsUnaligned = Alignment &&
3528 Alignment < TD->getABITypeAlignment(OperandType);
3532 if (IsVolatile || IsUnaligned) {
3535 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3536 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3539 if (IsVolatile) Out << "volatile ";
3545 writeOperand(Operand);
3547 if (IsVolatile || IsUnaligned) {
3554 void CWriter::visitLoadInst(LoadInst &I) {
3555 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3560 void CWriter::visitStoreInst(StoreInst &I) {
3561 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3562 I.isVolatile(), I.getAlignment());
3564 Value *Operand = I.getOperand(0);
3565 Constant *BitMask = 0;
3566 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3567 if (!ITy->isPowerOf2ByteWidth())
3568 // We have a bit width that doesn't match an even power-of-2 byte
3569 // size. Consequently we must & the value with the type's bit mask
3570 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3573 writeOperand(Operand);
3576 printConstant(BitMask, false);
3581 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3582 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3583 gep_type_end(I), false);
3586 void CWriter::visitVAArgInst(VAArgInst &I) {
3587 Out << "va_arg(*(va_list*)";
3588 writeOperand(I.getOperand(0));
3590 printType(Out, I.getType());
3594 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3595 const Type *EltTy = I.getType()->getElementType();
3596 writeOperand(I.getOperand(0));
3599 printType(Out, PointerType::getUnqual(EltTy));
3600 Out << ")(&" << GetValueName(&I) << "))[";
3601 writeOperand(I.getOperand(2));
3603 writeOperand(I.getOperand(1));
3607 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3608 // We know that our operand is not inlined.
3611 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3612 printType(Out, PointerType::getUnqual(EltTy));
3613 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3614 writeOperand(I.getOperand(1));
3618 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3620 printType(Out, SVI.getType());
3622 const VectorType *VT = SVI.getType();
3623 unsigned NumElts = VT->getNumElements();
3624 const Type *EltTy = VT->getElementType();
3626 for (unsigned i = 0; i != NumElts; ++i) {
3628 int SrcVal = SVI.getMaskValue(i);
3629 if ((unsigned)SrcVal >= NumElts*2) {
3630 Out << " 0/*undef*/ ";
3632 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3633 if (isa<Instruction>(Op)) {
3634 // Do an extractelement of this value from the appropriate input.
3636 printType(Out, PointerType::getUnqual(EltTy));
3637 Out << ")(&" << GetValueName(Op)
3638 << "))[" << (SrcVal & (NumElts-1)) << "]";
3639 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3642 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3651 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3652 // Start by copying the entire aggregate value into the result variable.
3653 writeOperand(IVI.getOperand(0));
3656 // Then do the insert to update the field.
3657 Out << GetValueName(&IVI);
3658 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3660 const Type *IndexedTy =
3661 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3662 if (isa<ArrayType>(IndexedTy))
3663 Out << ".array[" << *i << "]";
3665 Out << ".field" << *i;
3668 writeOperand(IVI.getOperand(1));
3671 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3673 if (isa<UndefValue>(EVI.getOperand(0))) {
3675 printType(Out, EVI.getType());
3676 Out << ") 0/*UNDEF*/";
3678 Out << GetValueName(EVI.getOperand(0));
3679 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3681 const Type *IndexedTy =
3682 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3683 if (isa<ArrayType>(IndexedTy))
3684 Out << ".array[" << *i << "]";
3686 Out << ".field" << *i;
3692 //===----------------------------------------------------------------------===//
3693 // External Interface declaration
3694 //===----------------------------------------------------------------------===//
3696 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3697 formatted_raw_ostream &o,
3698 CodeGenFileType FileType,
3699 CodeGenOpt::Level OptLevel) {
3700 if (FileType != TargetMachine::AssemblyFile) return true;
3702 PM.add(createGCLoweringPass());
3703 PM.add(createLowerInvokePass());
3704 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3705 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3706 PM.add(new CWriter(o));
3707 PM.add(createGCInfoDeleter());