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 CBEMangle(const std::string &S) {
357 for (unsigned i = 0, e = S.size(); i != e; ++i)
358 if (isalnum(S[i]) || S[i] == '_') {
362 Result += 'A'+(S[i]&15);
363 Result += 'A'+((S[i]>>4)&15);
370 /// This method inserts names for any unnamed structure types that are used by
371 /// the program, and removes names from structure types that are not used by the
374 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
375 // Get a set of types that are used by the program...
376 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
378 // Loop over the module symbol table, removing types from UT that are
379 // already named, and removing names for types that are not used.
381 TypeSymbolTable &TST = M.getTypeSymbolTable();
382 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
384 TypeSymbolTable::iterator I = TI++;
386 // If this isn't a struct or array type, remove it from our set of types
387 // to name. This simplifies emission later.
388 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
389 !isa<ArrayType>(I->second)) {
392 // If this is not used, remove it from the symbol table.
393 std::set<const Type *>::iterator UTI = UT.find(I->second);
397 UT.erase(UTI); // Only keep one name for this type.
401 // UT now contains types that are not named. Loop over it, naming
404 bool Changed = false;
405 unsigned RenameCounter = 0;
406 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
408 if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
409 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
415 // Loop over all external functions and globals. If we have two with
416 // identical names, merge them.
417 // FIXME: This code should disappear when we don't allow values with the same
418 // names when they have different types!
419 std::map<std::string, GlobalValue*> ExtSymbols;
420 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
422 if (GV->isDeclaration() && GV->hasName()) {
423 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
424 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
426 // Found a conflict, replace this global with the previous one.
427 GlobalValue *OldGV = X.first->second;
428 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
429 GV->eraseFromParent();
434 // Do the same for globals.
435 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
437 GlobalVariable *GV = I++;
438 if (GV->isDeclaration() && GV->hasName()) {
439 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
440 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
442 // Found a conflict, replace this global with the previous one.
443 GlobalValue *OldGV = X.first->second;
444 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
445 GV->eraseFromParent();
454 /// printStructReturnPointerFunctionType - This is like printType for a struct
455 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
456 /// print it as "Struct (*)(...)", for struct return functions.
457 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
458 const AttrListPtr &PAL,
459 const PointerType *TheTy) {
460 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
461 std::stringstream FunctionInnards;
462 FunctionInnards << " (*) (";
463 bool PrintedType = false;
465 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
466 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
468 for (++I, ++Idx; I != E; ++I, ++Idx) {
470 FunctionInnards << ", ";
471 const Type *ArgTy = *I;
472 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
473 assert(isa<PointerType>(ArgTy));
474 ArgTy = cast<PointerType>(ArgTy)->getElementType();
476 printType(FunctionInnards, ArgTy,
477 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
480 if (FTy->isVarArg()) {
482 FunctionInnards << ", ...";
483 } else if (!PrintedType) {
484 FunctionInnards << "void";
486 FunctionInnards << ')';
487 std::string tstr = FunctionInnards.str();
488 printType(Out, RetTy,
489 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
493 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
495 const std::string &NameSoFar) {
496 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
497 "Invalid type for printSimpleType");
498 switch (Ty->getTypeID()) {
499 case Type::VoidTyID: return Out << "void " << NameSoFar;
500 case Type::IntegerTyID: {
501 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
503 return Out << "bool " << NameSoFar;
504 else if (NumBits <= 8)
505 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
506 else if (NumBits <= 16)
507 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
508 else if (NumBits <= 32)
509 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
510 else if (NumBits <= 64)
511 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
513 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
514 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
517 case Type::FloatTyID: return Out << "float " << NameSoFar;
518 case Type::DoubleTyID: return Out << "double " << NameSoFar;
519 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
520 // present matches host 'long double'.
521 case Type::X86_FP80TyID:
522 case Type::PPC_FP128TyID:
523 case Type::FP128TyID: return Out << "long double " << NameSoFar;
525 case Type::VectorTyID: {
526 const VectorType *VTy = cast<VectorType>(Ty);
527 return printSimpleType(Out, VTy->getElementType(), isSigned,
528 " __attribute__((vector_size(" +
529 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
534 errs() << "Unknown primitive type: " << *Ty << "\n";
541 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
542 const std::string &NameSoFar) {
543 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
544 "Invalid type for printSimpleType");
545 switch (Ty->getTypeID()) {
546 case Type::VoidTyID: return Out << "void " << NameSoFar;
547 case Type::IntegerTyID: {
548 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
550 return Out << "bool " << NameSoFar;
551 else if (NumBits <= 8)
552 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
553 else if (NumBits <= 16)
554 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
555 else if (NumBits <= 32)
556 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
557 else if (NumBits <= 64)
558 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
560 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
561 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
564 case Type::FloatTyID: return Out << "float " << NameSoFar;
565 case Type::DoubleTyID: return Out << "double " << NameSoFar;
566 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
567 // present matches host 'long double'.
568 case Type::X86_FP80TyID:
569 case Type::PPC_FP128TyID:
570 case Type::FP128TyID: return Out << "long double " << NameSoFar;
572 case Type::VectorTyID: {
573 const VectorType *VTy = cast<VectorType>(Ty);
574 return printSimpleType(Out, VTy->getElementType(), isSigned,
575 " __attribute__((vector_size(" +
576 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
581 errs() << "Unknown primitive type: " << *Ty << "\n";
587 // Pass the Type* and the variable name and this prints out the variable
590 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
592 bool isSigned, const std::string &NameSoFar,
593 bool IgnoreName, const AttrListPtr &PAL) {
594 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
595 printSimpleType(Out, Ty, isSigned, NameSoFar);
599 // Check to see if the type is named.
600 if (!IgnoreName || isa<OpaqueType>(Ty)) {
601 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
602 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
605 switch (Ty->getTypeID()) {
606 case Type::FunctionTyID: {
607 const FunctionType *FTy = cast<FunctionType>(Ty);
608 std::stringstream FunctionInnards;
609 FunctionInnards << " (" << NameSoFar << ") (";
611 for (FunctionType::param_iterator I = FTy->param_begin(),
612 E = FTy->param_end(); I != E; ++I) {
613 const Type *ArgTy = *I;
614 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
615 assert(isa<PointerType>(ArgTy));
616 ArgTy = cast<PointerType>(ArgTy)->getElementType();
618 if (I != FTy->param_begin())
619 FunctionInnards << ", ";
620 printType(FunctionInnards, ArgTy,
621 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
624 if (FTy->isVarArg()) {
625 if (FTy->getNumParams())
626 FunctionInnards << ", ...";
627 } else if (!FTy->getNumParams()) {
628 FunctionInnards << "void";
630 FunctionInnards << ')';
631 std::string tstr = FunctionInnards.str();
632 printType(Out, FTy->getReturnType(),
633 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
636 case Type::StructTyID: {
637 const StructType *STy = cast<StructType>(Ty);
638 Out << NameSoFar + " {\n";
640 for (StructType::element_iterator I = STy->element_begin(),
641 E = STy->element_end(); I != E; ++I) {
643 printType(Out, *I, false, "field" + utostr(Idx++));
648 Out << " __attribute__ ((packed))";
652 case Type::PointerTyID: {
653 const PointerType *PTy = cast<PointerType>(Ty);
654 std::string ptrName = "*" + NameSoFar;
656 if (isa<ArrayType>(PTy->getElementType()) ||
657 isa<VectorType>(PTy->getElementType()))
658 ptrName = "(" + ptrName + ")";
661 // Must be a function ptr cast!
662 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
663 return printType(Out, PTy->getElementType(), false, ptrName);
666 case Type::ArrayTyID: {
667 const ArrayType *ATy = cast<ArrayType>(Ty);
668 unsigned NumElements = ATy->getNumElements();
669 if (NumElements == 0) NumElements = 1;
670 // Arrays are wrapped in structs to allow them to have normal
671 // value semantics (avoiding the array "decay").
672 Out << NameSoFar << " { ";
673 printType(Out, ATy->getElementType(), false,
674 "array[" + utostr(NumElements) + "]");
678 case Type::OpaqueTyID: {
679 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
680 assert(TypeNames.find(Ty) == TypeNames.end());
681 TypeNames[Ty] = TyName;
682 return Out << TyName << ' ' << NameSoFar;
685 llvm_unreachable("Unhandled case in getTypeProps!");
691 // Pass the Type* and the variable name and this prints out the variable
694 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
695 bool isSigned, const std::string &NameSoFar,
696 bool IgnoreName, const AttrListPtr &PAL) {
697 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
698 printSimpleType(Out, Ty, isSigned, NameSoFar);
702 // Check to see if the type is named.
703 if (!IgnoreName || isa<OpaqueType>(Ty)) {
704 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
705 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
708 switch (Ty->getTypeID()) {
709 case Type::FunctionTyID: {
710 const FunctionType *FTy = cast<FunctionType>(Ty);
711 std::stringstream FunctionInnards;
712 FunctionInnards << " (" << NameSoFar << ") (";
714 for (FunctionType::param_iterator I = FTy->param_begin(),
715 E = FTy->param_end(); I != E; ++I) {
716 const Type *ArgTy = *I;
717 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
718 assert(isa<PointerType>(ArgTy));
719 ArgTy = cast<PointerType>(ArgTy)->getElementType();
721 if (I != FTy->param_begin())
722 FunctionInnards << ", ";
723 printType(FunctionInnards, ArgTy,
724 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
727 if (FTy->isVarArg()) {
728 if (FTy->getNumParams())
729 FunctionInnards << ", ...";
730 } else if (!FTy->getNumParams()) {
731 FunctionInnards << "void";
733 FunctionInnards << ')';
734 std::string tstr = FunctionInnards.str();
735 printType(Out, FTy->getReturnType(),
736 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
739 case Type::StructTyID: {
740 const StructType *STy = cast<StructType>(Ty);
741 Out << NameSoFar + " {\n";
743 for (StructType::element_iterator I = STy->element_begin(),
744 E = STy->element_end(); I != E; ++I) {
746 printType(Out, *I, false, "field" + utostr(Idx++));
751 Out << " __attribute__ ((packed))";
755 case Type::PointerTyID: {
756 const PointerType *PTy = cast<PointerType>(Ty);
757 std::string ptrName = "*" + NameSoFar;
759 if (isa<ArrayType>(PTy->getElementType()) ||
760 isa<VectorType>(PTy->getElementType()))
761 ptrName = "(" + ptrName + ")";
764 // Must be a function ptr cast!
765 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
766 return printType(Out, PTy->getElementType(), false, ptrName);
769 case Type::ArrayTyID: {
770 const ArrayType *ATy = cast<ArrayType>(Ty);
771 unsigned NumElements = ATy->getNumElements();
772 if (NumElements == 0) NumElements = 1;
773 // Arrays are wrapped in structs to allow them to have normal
774 // value semantics (avoiding the array "decay").
775 Out << NameSoFar << " { ";
776 printType(Out, ATy->getElementType(), false,
777 "array[" + utostr(NumElements) + "]");
781 case Type::OpaqueTyID: {
782 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
783 assert(TypeNames.find(Ty) == TypeNames.end());
784 TypeNames[Ty] = TyName;
785 return Out << TyName << ' ' << NameSoFar;
788 llvm_unreachable("Unhandled case in getTypeProps!");
794 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
796 // As a special case, print the array as a string if it is an array of
797 // ubytes or an array of sbytes with positive values.
799 const Type *ETy = CPA->getType()->getElementType();
800 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
801 ETy == Type::getInt8Ty(CPA->getContext()));
803 // Make sure the last character is a null char, as automatically added by C
804 if (isString && (CPA->getNumOperands() == 0 ||
805 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
810 // Keep track of whether the last number was a hexadecimal escape
811 bool LastWasHex = false;
813 // Do not include the last character, which we know is null
814 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
815 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
817 // Print it out literally if it is a printable character. The only thing
818 // to be careful about is when the last letter output was a hex escape
819 // code, in which case we have to be careful not to print out hex digits
820 // explicitly (the C compiler thinks it is a continuation of the previous
821 // character, sheesh...)
823 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
825 if (C == '"' || C == '\\')
826 Out << "\\" << (char)C;
832 case '\n': Out << "\\n"; break;
833 case '\t': Out << "\\t"; break;
834 case '\r': Out << "\\r"; break;
835 case '\v': Out << "\\v"; break;
836 case '\a': Out << "\\a"; break;
837 case '\"': Out << "\\\""; break;
838 case '\'': Out << "\\\'"; break;
841 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
842 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
851 if (CPA->getNumOperands()) {
853 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
854 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
856 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
863 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
865 if (CP->getNumOperands()) {
867 printConstant(cast<Constant>(CP->getOperand(0)), Static);
868 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
870 printConstant(cast<Constant>(CP->getOperand(i)), Static);
876 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
877 // textually as a double (rather than as a reference to a stack-allocated
878 // variable). We decide this by converting CFP to a string and back into a
879 // double, and then checking whether the conversion results in a bit-equal
880 // double to the original value of CFP. This depends on us and the target C
881 // compiler agreeing on the conversion process (which is pretty likely since we
882 // only deal in IEEE FP).
884 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
886 // Do long doubles in hex for now.
887 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
888 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
890 APFloat APF = APFloat(CFP->getValueAPF()); // copy
891 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
892 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
893 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
895 sprintf(Buffer, "%a", APF.convertToDouble());
896 if (!strncmp(Buffer, "0x", 2) ||
897 !strncmp(Buffer, "-0x", 3) ||
898 !strncmp(Buffer, "+0x", 3))
899 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
902 std::string StrVal = ftostr(APF);
904 while (StrVal[0] == ' ')
905 StrVal.erase(StrVal.begin());
907 // Check to make sure that the stringized number is not some string like "Inf"
908 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
909 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
910 ((StrVal[0] == '-' || StrVal[0] == '+') &&
911 (StrVal[1] >= '0' && StrVal[1] <= '9')))
912 // Reparse stringized version!
913 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
918 /// Print out the casting for a cast operation. This does the double casting
919 /// necessary for conversion to the destination type, if necessary.
920 /// @brief Print a cast
921 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
922 // Print the destination type cast
924 case Instruction::UIToFP:
925 case Instruction::SIToFP:
926 case Instruction::IntToPtr:
927 case Instruction::Trunc:
928 case Instruction::BitCast:
929 case Instruction::FPExt:
930 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
932 printType(Out, DstTy);
935 case Instruction::ZExt:
936 case Instruction::PtrToInt:
937 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
939 printSimpleType(Out, DstTy, false);
942 case Instruction::SExt:
943 case Instruction::FPToSI: // For these, make sure we get a signed dest
945 printSimpleType(Out, DstTy, true);
949 llvm_unreachable("Invalid cast opcode");
952 // Print the source type cast
954 case Instruction::UIToFP:
955 case Instruction::ZExt:
957 printSimpleType(Out, SrcTy, false);
960 case Instruction::SIToFP:
961 case Instruction::SExt:
963 printSimpleType(Out, SrcTy, true);
966 case Instruction::IntToPtr:
967 case Instruction::PtrToInt:
968 // Avoid "cast to pointer from integer of different size" warnings
969 Out << "(unsigned long)";
971 case Instruction::Trunc:
972 case Instruction::BitCast:
973 case Instruction::FPExt:
974 case Instruction::FPTrunc:
975 case Instruction::FPToSI:
976 case Instruction::FPToUI:
977 break; // These don't need a source cast.
979 llvm_unreachable("Invalid cast opcode");
984 // printConstant - The LLVM Constant to C Constant converter.
985 void CWriter::printConstant(Constant *CPV, bool Static) {
986 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
987 switch (CE->getOpcode()) {
988 case Instruction::Trunc:
989 case Instruction::ZExt:
990 case Instruction::SExt:
991 case Instruction::FPTrunc:
992 case Instruction::FPExt:
993 case Instruction::UIToFP:
994 case Instruction::SIToFP:
995 case Instruction::FPToUI:
996 case Instruction::FPToSI:
997 case Instruction::PtrToInt:
998 case Instruction::IntToPtr:
999 case Instruction::BitCast:
1001 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
1002 if (CE->getOpcode() == Instruction::SExt &&
1003 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
1004 // Make sure we really sext from bool here by subtracting from 0
1007 printConstant(CE->getOperand(0), Static);
1008 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
1009 (CE->getOpcode() == Instruction::Trunc ||
1010 CE->getOpcode() == Instruction::FPToUI ||
1011 CE->getOpcode() == Instruction::FPToSI ||
1012 CE->getOpcode() == Instruction::PtrToInt)) {
1013 // Make sure we really truncate to bool here by anding with 1
1019 case Instruction::GetElementPtr:
1021 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
1022 gep_type_end(CPV), Static);
1025 case Instruction::Select:
1027 printConstant(CE->getOperand(0), Static);
1029 printConstant(CE->getOperand(1), Static);
1031 printConstant(CE->getOperand(2), Static);
1034 case Instruction::Add:
1035 case Instruction::FAdd:
1036 case Instruction::Sub:
1037 case Instruction::FSub:
1038 case Instruction::Mul:
1039 case Instruction::FMul:
1040 case Instruction::SDiv:
1041 case Instruction::UDiv:
1042 case Instruction::FDiv:
1043 case Instruction::URem:
1044 case Instruction::SRem:
1045 case Instruction::FRem:
1046 case Instruction::And:
1047 case Instruction::Or:
1048 case Instruction::Xor:
1049 case Instruction::ICmp:
1050 case Instruction::Shl:
1051 case Instruction::LShr:
1052 case Instruction::AShr:
1055 bool NeedsClosingParens = printConstExprCast(CE, Static);
1056 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1057 switch (CE->getOpcode()) {
1058 case Instruction::Add:
1059 case Instruction::FAdd: Out << " + "; break;
1060 case Instruction::Sub:
1061 case Instruction::FSub: Out << " - "; break;
1062 case Instruction::Mul:
1063 case Instruction::FMul: Out << " * "; break;
1064 case Instruction::URem:
1065 case Instruction::SRem:
1066 case Instruction::FRem: Out << " % "; break;
1067 case Instruction::UDiv:
1068 case Instruction::SDiv:
1069 case Instruction::FDiv: Out << " / "; break;
1070 case Instruction::And: Out << " & "; break;
1071 case Instruction::Or: Out << " | "; break;
1072 case Instruction::Xor: Out << " ^ "; break;
1073 case Instruction::Shl: Out << " << "; break;
1074 case Instruction::LShr:
1075 case Instruction::AShr: Out << " >> "; break;
1076 case Instruction::ICmp:
1077 switch (CE->getPredicate()) {
1078 case ICmpInst::ICMP_EQ: Out << " == "; break;
1079 case ICmpInst::ICMP_NE: Out << " != "; break;
1080 case ICmpInst::ICMP_SLT:
1081 case ICmpInst::ICMP_ULT: Out << " < "; break;
1082 case ICmpInst::ICMP_SLE:
1083 case ICmpInst::ICMP_ULE: Out << " <= "; break;
1084 case ICmpInst::ICMP_SGT:
1085 case ICmpInst::ICMP_UGT: Out << " > "; break;
1086 case ICmpInst::ICMP_SGE:
1087 case ICmpInst::ICMP_UGE: Out << " >= "; break;
1088 default: llvm_unreachable("Illegal ICmp predicate");
1091 default: llvm_unreachable("Illegal opcode here!");
1093 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1094 if (NeedsClosingParens)
1099 case Instruction::FCmp: {
1101 bool NeedsClosingParens = printConstExprCast(CE, Static);
1102 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
1104 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
1108 switch (CE->getPredicate()) {
1109 default: llvm_unreachable("Illegal FCmp predicate");
1110 case FCmpInst::FCMP_ORD: op = "ord"; break;
1111 case FCmpInst::FCMP_UNO: op = "uno"; break;
1112 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
1113 case FCmpInst::FCMP_UNE: op = "une"; break;
1114 case FCmpInst::FCMP_ULT: op = "ult"; break;
1115 case FCmpInst::FCMP_ULE: op = "ule"; break;
1116 case FCmpInst::FCMP_UGT: op = "ugt"; break;
1117 case FCmpInst::FCMP_UGE: op = "uge"; break;
1118 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
1119 case FCmpInst::FCMP_ONE: op = "one"; break;
1120 case FCmpInst::FCMP_OLT: op = "olt"; break;
1121 case FCmpInst::FCMP_OLE: op = "ole"; break;
1122 case FCmpInst::FCMP_OGT: op = "ogt"; break;
1123 case FCmpInst::FCMP_OGE: op = "oge"; break;
1125 Out << "llvm_fcmp_" << op << "(";
1126 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
1128 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
1131 if (NeedsClosingParens)
1138 errs() << "CWriter Error: Unhandled constant expression: "
1141 llvm_unreachable(0);
1143 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1145 printType(Out, CPV->getType()); // sign doesn't matter
1146 Out << ")/*UNDEF*/";
1147 if (!isa<VectorType>(CPV->getType())) {
1155 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1156 const Type* Ty = CI->getType();
1157 if (Ty == Type::getInt1Ty(CPV->getContext()))
1158 Out << (CI->getZExtValue() ? '1' : '0');
1159 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1160 Out << CI->getZExtValue() << 'u';
1161 else if (Ty->getPrimitiveSizeInBits() > 32)
1162 Out << CI->getZExtValue() << "ull";
1165 printSimpleType(Out, Ty, false) << ')';
1166 if (CI->isMinValue(true))
1167 Out << CI->getZExtValue() << 'u';
1169 Out << CI->getSExtValue();
1175 switch (CPV->getType()->getTypeID()) {
1176 case Type::FloatTyID:
1177 case Type::DoubleTyID:
1178 case Type::X86_FP80TyID:
1179 case Type::PPC_FP128TyID:
1180 case Type::FP128TyID: {
1181 ConstantFP *FPC = cast<ConstantFP>(CPV);
1182 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1183 if (I != FPConstantMap.end()) {
1184 // Because of FP precision problems we must load from a stack allocated
1185 // value that holds the value in hex.
1186 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1188 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1191 << "*)&FPConstant" << I->second << ')';
1194 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1195 V = FPC->getValueAPF().convertToFloat();
1196 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1197 V = FPC->getValueAPF().convertToDouble();
1199 // Long double. Convert the number to double, discarding precision.
1200 // This is not awesome, but it at least makes the CBE output somewhat
1202 APFloat Tmp = FPC->getValueAPF();
1204 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1205 V = Tmp.convertToDouble();
1211 // FIXME the actual NaN bits should be emitted.
1212 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1214 const unsigned long QuietNaN = 0x7ff8UL;
1215 //const unsigned long SignalNaN = 0x7ff4UL;
1217 // We need to grab the first part of the FP #
1220 uint64_t ll = DoubleToBits(V);
1221 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1223 std::string Num(&Buffer[0], &Buffer[6]);
1224 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1226 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1227 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1228 << Buffer << "\") /*nan*/ ";
1230 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1231 << Buffer << "\") /*nan*/ ";
1232 } else if (IsInf(V)) {
1234 if (V < 0) Out << '-';
1235 Out << "LLVM_INF" <<
1236 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1240 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1241 // Print out the constant as a floating point number.
1243 sprintf(Buffer, "%a", V);
1246 Num = ftostr(FPC->getValueAPF());
1254 case Type::ArrayTyID:
1255 // Use C99 compound expression literal initializer syntax.
1258 printType(Out, CPV->getType());
1261 Out << "{ "; // Arrays are wrapped in struct types.
1262 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1263 printConstantArray(CA, Static);
1265 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1266 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1268 if (AT->getNumElements()) {
1270 Constant *CZ = Constant::getNullValue(AT->getElementType());
1271 printConstant(CZ, Static);
1272 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1274 printConstant(CZ, Static);
1279 Out << " }"; // Arrays are wrapped in struct types.
1282 case Type::VectorTyID:
1283 // Use C99 compound expression literal initializer syntax.
1286 printType(Out, CPV->getType());
1289 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1290 printConstantVector(CV, Static);
1292 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1293 const VectorType *VT = cast<VectorType>(CPV->getType());
1295 Constant *CZ = Constant::getNullValue(VT->getElementType());
1296 printConstant(CZ, Static);
1297 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1299 printConstant(CZ, Static);
1305 case Type::StructTyID:
1306 // Use C99 compound expression literal initializer syntax.
1309 printType(Out, CPV->getType());
1312 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1313 const StructType *ST = cast<StructType>(CPV->getType());
1315 if (ST->getNumElements()) {
1317 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1318 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1320 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1326 if (CPV->getNumOperands()) {
1328 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1329 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1331 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1338 case Type::PointerTyID:
1339 if (isa<ConstantPointerNull>(CPV)) {
1341 printType(Out, CPV->getType()); // sign doesn't matter
1342 Out << ")/*NULL*/0)";
1344 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1345 writeOperand(GV, Static);
1351 errs() << "Unknown constant type: " << *CPV << "\n";
1353 llvm_unreachable(0);
1357 // Some constant expressions need to be casted back to the original types
1358 // because their operands were casted to the expected type. This function takes
1359 // care of detecting that case and printing the cast for the ConstantExpr.
1360 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1361 bool NeedsExplicitCast = false;
1362 const Type *Ty = CE->getOperand(0)->getType();
1363 bool TypeIsSigned = false;
1364 switch (CE->getOpcode()) {
1365 case Instruction::Add:
1366 case Instruction::Sub:
1367 case Instruction::Mul:
1368 // We need to cast integer arithmetic so that it is always performed
1369 // as unsigned, to avoid undefined behavior on overflow.
1370 case Instruction::LShr:
1371 case Instruction::URem:
1372 case Instruction::UDiv: NeedsExplicitCast = true; break;
1373 case Instruction::AShr:
1374 case Instruction::SRem:
1375 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1376 case Instruction::SExt:
1378 NeedsExplicitCast = true;
1379 TypeIsSigned = true;
1381 case Instruction::ZExt:
1382 case Instruction::Trunc:
1383 case Instruction::FPTrunc:
1384 case Instruction::FPExt:
1385 case Instruction::UIToFP:
1386 case Instruction::SIToFP:
1387 case Instruction::FPToUI:
1388 case Instruction::FPToSI:
1389 case Instruction::PtrToInt:
1390 case Instruction::IntToPtr:
1391 case Instruction::BitCast:
1393 NeedsExplicitCast = true;
1397 if (NeedsExplicitCast) {
1399 if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
1400 printSimpleType(Out, Ty, TypeIsSigned);
1402 printType(Out, Ty); // not integer, sign doesn't matter
1405 return NeedsExplicitCast;
1408 // Print a constant assuming that it is the operand for a given Opcode. The
1409 // opcodes that care about sign need to cast their operands to the expected
1410 // type before the operation proceeds. This function does the casting.
1411 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1413 // Extract the operand's type, we'll need it.
1414 const Type* OpTy = CPV->getType();
1416 // Indicate whether to do the cast or not.
1417 bool shouldCast = false;
1418 bool typeIsSigned = false;
1420 // Based on the Opcode for which this Constant is being written, determine
1421 // the new type to which the operand should be casted by setting the value
1422 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1426 // for most instructions, it doesn't matter
1428 case Instruction::Add:
1429 case Instruction::Sub:
1430 case Instruction::Mul:
1431 // We need to cast integer arithmetic so that it is always performed
1432 // as unsigned, to avoid undefined behavior on overflow.
1433 case Instruction::LShr:
1434 case Instruction::UDiv:
1435 case Instruction::URem:
1438 case Instruction::AShr:
1439 case Instruction::SDiv:
1440 case Instruction::SRem:
1442 typeIsSigned = true;
1446 // Write out the casted constant if we should, otherwise just write the
1450 printSimpleType(Out, OpTy, typeIsSigned);
1452 printConstant(CPV, false);
1455 printConstant(CPV, false);
1458 std::string CWriter::GetValueName(const Value *Operand) {
1459 // Mangle globals with the standard mangler interface for LLC compatibility.
1460 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1461 SmallString<128> Str;
1462 Mang->getNameWithPrefix(Str, GV, false);
1463 return CBEMangle(Str.str().str());
1466 std::string Name = Operand->getName();
1468 if (Name.empty()) { // Assign unique names to local temporaries.
1469 unsigned &No = AnonValueNumbers[Operand];
1471 No = ++NextAnonValueNumber;
1472 Name = "tmp__" + utostr(No);
1475 std::string VarName;
1476 VarName.reserve(Name.capacity());
1478 for (std::string::iterator I = Name.begin(), E = Name.end();
1482 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1483 (ch >= '0' && ch <= '9') || ch == '_')) {
1485 sprintf(buffer, "_%x_", ch);
1491 return "llvm_cbe_" + VarName;
1494 /// writeInstComputationInline - Emit the computation for the specified
1495 /// instruction inline, with no destination provided.
1496 void CWriter::writeInstComputationInline(Instruction &I) {
1497 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1499 const Type *Ty = I.getType();
1500 if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1501 Ty!=Type::getInt8Ty(I.getContext()) &&
1502 Ty!=Type::getInt16Ty(I.getContext()) &&
1503 Ty!=Type::getInt32Ty(I.getContext()) &&
1504 Ty!=Type::getInt64Ty(I.getContext()))) {
1505 llvm_report_error("The C backend does not currently support integer "
1506 "types of widths other than 1, 8, 16, 32, 64.\n"
1507 "This is being tracked as PR 4158.");
1510 // If this is a non-trivial bool computation, make sure to truncate down to
1511 // a 1 bit value. This is important because we want "add i1 x, y" to return
1512 // "0" when x and y are true, not "2" for example.
1513 bool NeedBoolTrunc = false;
1514 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1515 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1516 NeedBoolTrunc = true;
1528 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1529 if (Instruction *I = dyn_cast<Instruction>(Operand))
1530 // Should we inline this instruction to build a tree?
1531 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1533 writeInstComputationInline(*I);
1538 Constant* CPV = dyn_cast<Constant>(Operand);
1540 if (CPV && !isa<GlobalValue>(CPV))
1541 printConstant(CPV, Static);
1543 Out << GetValueName(Operand);
1546 void CWriter::writeOperand(Value *Operand, bool Static) {
1547 bool isAddressImplicit = isAddressExposed(Operand);
1548 if (isAddressImplicit)
1549 Out << "(&"; // Global variables are referenced as their addresses by llvm
1551 writeOperandInternal(Operand, Static);
1553 if (isAddressImplicit)
1557 // Some instructions need to have their result value casted back to the
1558 // original types because their operands were casted to the expected type.
1559 // This function takes care of detecting that case and printing the cast
1560 // for the Instruction.
1561 bool CWriter::writeInstructionCast(const Instruction &I) {
1562 const Type *Ty = I.getOperand(0)->getType();
1563 switch (I.getOpcode()) {
1564 case Instruction::Add:
1565 case Instruction::Sub:
1566 case Instruction::Mul:
1567 // We need to cast integer arithmetic so that it is always performed
1568 // as unsigned, to avoid undefined behavior on overflow.
1569 case Instruction::LShr:
1570 case Instruction::URem:
1571 case Instruction::UDiv:
1573 printSimpleType(Out, Ty, false);
1576 case Instruction::AShr:
1577 case Instruction::SRem:
1578 case Instruction::SDiv:
1580 printSimpleType(Out, Ty, true);
1588 // Write the operand with a cast to another type based on the Opcode being used.
1589 // This will be used in cases where an instruction has specific type
1590 // requirements (usually signedness) for its operands.
1591 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1593 // Extract the operand's type, we'll need it.
1594 const Type* OpTy = Operand->getType();
1596 // Indicate whether to do the cast or not.
1597 bool shouldCast = false;
1599 // Indicate whether the cast should be to a signed type or not.
1600 bool castIsSigned = false;
1602 // Based on the Opcode for which this Operand is being written, determine
1603 // the new type to which the operand should be casted by setting the value
1604 // of OpTy. If we change OpTy, also set shouldCast to true.
1607 // for most instructions, it doesn't matter
1609 case Instruction::Add:
1610 case Instruction::Sub:
1611 case Instruction::Mul:
1612 // We need to cast integer arithmetic so that it is always performed
1613 // as unsigned, to avoid undefined behavior on overflow.
1614 case Instruction::LShr:
1615 case Instruction::UDiv:
1616 case Instruction::URem: // Cast to unsigned first
1618 castIsSigned = false;
1620 case Instruction::GetElementPtr:
1621 case Instruction::AShr:
1622 case Instruction::SDiv:
1623 case Instruction::SRem: // Cast to signed first
1625 castIsSigned = true;
1629 // Write out the casted operand if we should, otherwise just write the
1633 printSimpleType(Out, OpTy, castIsSigned);
1635 writeOperand(Operand);
1638 writeOperand(Operand);
1641 // Write the operand with a cast to another type based on the icmp predicate
1643 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1644 // This has to do a cast to ensure the operand has the right signedness.
1645 // Also, if the operand is a pointer, we make sure to cast to an integer when
1646 // doing the comparison both for signedness and so that the C compiler doesn't
1647 // optimize things like "p < NULL" to false (p may contain an integer value
1649 bool shouldCast = Cmp.isRelational();
1651 // Write out the casted operand if we should, otherwise just write the
1654 writeOperand(Operand);
1658 // Should this be a signed comparison? If so, convert to signed.
1659 bool castIsSigned = Cmp.isSigned();
1661 // If the operand was a pointer, convert to a large integer type.
1662 const Type* OpTy = Operand->getType();
1663 if (isa<PointerType>(OpTy))
1664 OpTy = TD->getIntPtrType(Operand->getContext());
1667 printSimpleType(Out, OpTy, castIsSigned);
1669 writeOperand(Operand);
1673 // generateCompilerSpecificCode - This is where we add conditional compilation
1674 // directives to cater to specific compilers as need be.
1676 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1677 const TargetData *TD) {
1678 // Alloca is hard to get, and we don't want to include stdlib.h here.
1679 Out << "/* get a declaration for alloca */\n"
1680 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1681 << "#define alloca(x) __builtin_alloca((x))\n"
1682 << "#define _alloca(x) __builtin_alloca((x))\n"
1683 << "#elif defined(__APPLE__)\n"
1684 << "extern void *__builtin_alloca(unsigned long);\n"
1685 << "#define alloca(x) __builtin_alloca(x)\n"
1686 << "#define longjmp _longjmp\n"
1687 << "#define setjmp _setjmp\n"
1688 << "#elif defined(__sun__)\n"
1689 << "#if defined(__sparcv9)\n"
1690 << "extern void *__builtin_alloca(unsigned long);\n"
1692 << "extern void *__builtin_alloca(unsigned int);\n"
1694 << "#define alloca(x) __builtin_alloca(x)\n"
1695 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1696 << "#define alloca(x) __builtin_alloca(x)\n"
1697 << "#elif defined(_MSC_VER)\n"
1698 << "#define inline _inline\n"
1699 << "#define alloca(x) _alloca(x)\n"
1701 << "#include <alloca.h>\n"
1704 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1705 // If we aren't being compiled with GCC, just drop these attributes.
1706 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1707 << "#define __attribute__(X)\n"
1710 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1711 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1712 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1713 << "#elif defined(__GNUC__)\n"
1714 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1716 << "#define __EXTERNAL_WEAK__\n"
1719 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1720 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1721 << "#define __ATTRIBUTE_WEAK__\n"
1722 << "#elif defined(__GNUC__)\n"
1723 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1725 << "#define __ATTRIBUTE_WEAK__\n"
1728 // Add hidden visibility support. FIXME: APPLE_CC?
1729 Out << "#if defined(__GNUC__)\n"
1730 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1733 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1734 // From the GCC documentation:
1736 // double __builtin_nan (const char *str)
1738 // This is an implementation of the ISO C99 function nan.
1740 // Since ISO C99 defines this function in terms of strtod, which we do
1741 // not implement, a description of the parsing is in order. The string is
1742 // parsed as by strtol; that is, the base is recognized by leading 0 or
1743 // 0x prefixes. The number parsed is placed in the significand such that
1744 // the least significant bit of the number is at the least significant
1745 // bit of the significand. The number is truncated to fit the significand
1746 // field provided. The significand is forced to be a quiet NaN.
1748 // This function, if given a string literal, is evaluated early enough
1749 // that it is considered a compile-time constant.
1751 // float __builtin_nanf (const char *str)
1753 // Similar to __builtin_nan, except the return type is float.
1755 // double __builtin_inf (void)
1757 // Similar to __builtin_huge_val, except a warning is generated if the
1758 // target floating-point format does not support infinities. This
1759 // function is suitable for implementing the ISO C99 macro INFINITY.
1761 // float __builtin_inff (void)
1763 // Similar to __builtin_inf, except the return type is float.
1764 Out << "#ifdef __GNUC__\n"
1765 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1766 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1767 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1768 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1769 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1770 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1771 << "#define LLVM_PREFETCH(addr,rw,locality) "
1772 "__builtin_prefetch(addr,rw,locality)\n"
1773 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1774 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1775 << "#define LLVM_ASM __asm__\n"
1777 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1778 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1779 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1780 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1781 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1782 << "#define LLVM_INFF 0.0F /* Float */\n"
1783 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1784 << "#define __ATTRIBUTE_CTOR__\n"
1785 << "#define __ATTRIBUTE_DTOR__\n"
1786 << "#define LLVM_ASM(X)\n"
1789 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1790 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1791 << "#define __builtin_stack_restore(X) /* noop */\n"
1794 // Output typedefs for 128-bit integers. If these are needed with a
1795 // 32-bit target or with a C compiler that doesn't support mode(TI),
1796 // more drastic measures will be needed.
1797 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1798 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1799 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1802 // Output target-specific code that should be inserted into main.
1803 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1806 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1807 /// the StaticTors set.
1808 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1809 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1810 if (!InitList) return;
1812 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1813 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1814 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1816 if (CS->getOperand(1)->isNullValue())
1817 return; // Found a null terminator, exit printing.
1818 Constant *FP = CS->getOperand(1);
1819 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1821 FP = CE->getOperand(0);
1822 if (Function *F = dyn_cast<Function>(FP))
1823 StaticTors.insert(F);
1827 enum SpecialGlobalClass {
1829 GlobalCtors, GlobalDtors,
1833 /// getGlobalVariableClass - If this is a global that is specially recognized
1834 /// by LLVM, return a code that indicates how we should handle it.
1835 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1836 // If this is a global ctors/dtors list, handle it now.
1837 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1838 if (GV->getName() == "llvm.global_ctors")
1840 else if (GV->getName() == "llvm.global_dtors")
1844 // Otherwise, it it is other metadata, don't print it. This catches things
1845 // like debug information.
1846 if (GV->getSection() == "llvm.metadata")
1852 // PrintEscapedString - Print each character of the specified string, escaping
1853 // it if it is not printable or if it is an escape char.
1854 static void PrintEscapedString(const char *Str, unsigned Length,
1856 for (unsigned i = 0; i != Length; ++i) {
1857 unsigned char C = Str[i];
1858 if (isprint(C) && C != '\\' && C != '"')
1867 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1871 // PrintEscapedString - Print each character of the specified string, escaping
1872 // it if it is not printable or if it is an escape char.
1873 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1874 PrintEscapedString(Str.c_str(), Str.size(), Out);
1877 bool CWriter::doInitialization(Module &M) {
1878 FunctionPass::doInitialization(M);
1883 TD = new TargetData(&M);
1884 IL = new IntrinsicLowering(*TD);
1885 IL->AddPrototypes(M);
1888 std::string Triple = TheModule->getTargetTriple();
1890 Triple = llvm::sys::getHostTriple();
1893 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1894 TAsm = Match->createAsmInfo(Triple);
1896 TAsm = new CBEMCAsmInfo();
1897 Mang = new Mangler(*TAsm);
1899 // Keep track of which functions are static ctors/dtors so they can have
1900 // an attribute added to their prototypes.
1901 std::set<Function*> StaticCtors, StaticDtors;
1902 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1904 switch (getGlobalVariableClass(I)) {
1907 FindStaticTors(I, StaticCtors);
1910 FindStaticTors(I, StaticDtors);
1915 // get declaration for alloca
1916 Out << "/* Provide Declarations */\n";
1917 Out << "#include <stdarg.h>\n"; // Varargs support
1918 Out << "#include <setjmp.h>\n"; // Unwind support
1919 generateCompilerSpecificCode(Out, TD);
1921 // Provide a definition for `bool' if not compiling with a C++ compiler.
1923 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1925 << "\n\n/* Support for floating point constants */\n"
1926 << "typedef unsigned long long ConstantDoubleTy;\n"
1927 << "typedef unsigned int ConstantFloatTy;\n"
1928 << "typedef struct { unsigned long long f1; unsigned short f2; "
1929 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1930 // This is used for both kinds of 128-bit long double; meaning differs.
1931 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1932 " ConstantFP128Ty;\n"
1933 << "\n\n/* Global Declarations */\n";
1935 // First output all the declarations for the program, because C requires
1936 // Functions & globals to be declared before they are used.
1938 if (!M.getModuleInlineAsm().empty()) {
1939 Out << "/* Module asm statements */\n"
1942 // Split the string into lines, to make it easier to read the .ll file.
1943 std::string Asm = M.getModuleInlineAsm();
1945 size_t NewLine = Asm.find_first_of('\n', CurPos);
1946 while (NewLine != std::string::npos) {
1947 // We found a newline, print the portion of the asm string from the
1948 // last newline up to this newline.
1950 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1954 NewLine = Asm.find_first_of('\n', CurPos);
1957 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1959 << "/* End Module asm statements */\n";
1962 // Loop over the symbol table, emitting all named constants...
1963 printModuleTypes(M.getTypeSymbolTable());
1965 // Global variable declarations...
1966 if (!M.global_empty()) {
1967 Out << "\n/* External Global Variable Declarations */\n";
1968 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1971 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1972 I->hasCommonLinkage())
1974 else if (I->hasDLLImportLinkage())
1975 Out << "__declspec(dllimport) ";
1977 continue; // Internal Global
1979 // Thread Local Storage
1980 if (I->isThreadLocal())
1983 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1985 if (I->hasExternalWeakLinkage())
1986 Out << " __EXTERNAL_WEAK__";
1991 // Function declarations
1992 Out << "\n/* Function Declarations */\n";
1993 Out << "double fmod(double, double);\n"; // Support for FP rem
1994 Out << "float fmodf(float, float);\n";
1995 Out << "long double fmodl(long double, long double);\n";
1997 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1998 // Don't print declarations for intrinsic functions.
1999 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
2000 I->getName() != "longjmp" && I->getName() != "_setjmp") {
2001 if (I->hasExternalWeakLinkage())
2003 printFunctionSignature(I, true);
2004 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
2005 Out << " __ATTRIBUTE_WEAK__";
2006 if (I->hasExternalWeakLinkage())
2007 Out << " __EXTERNAL_WEAK__";
2008 if (StaticCtors.count(I))
2009 Out << " __ATTRIBUTE_CTOR__";
2010 if (StaticDtors.count(I))
2011 Out << " __ATTRIBUTE_DTOR__";
2012 if (I->hasHiddenVisibility())
2013 Out << " __HIDDEN__";
2015 if (I->hasName() && I->getName()[0] == 1)
2016 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
2022 // Output the global variable declarations
2023 if (!M.global_empty()) {
2024 Out << "\n\n/* Global Variable Declarations */\n";
2025 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2027 if (!I->isDeclaration()) {
2028 // Ignore special globals, such as debug info.
2029 if (getGlobalVariableClass(I))
2032 if (I->hasLocalLinkage())
2037 // Thread Local Storage
2038 if (I->isThreadLocal())
2041 printType(Out, I->getType()->getElementType(), false,
2044 if (I->hasLinkOnceLinkage())
2045 Out << " __attribute__((common))";
2046 else if (I->hasCommonLinkage()) // FIXME is this right?
2047 Out << " __ATTRIBUTE_WEAK__";
2048 else if (I->hasWeakLinkage())
2049 Out << " __ATTRIBUTE_WEAK__";
2050 else if (I->hasExternalWeakLinkage())
2051 Out << " __EXTERNAL_WEAK__";
2052 if (I->hasHiddenVisibility())
2053 Out << " __HIDDEN__";
2058 // Output the global variable definitions and contents...
2059 if (!M.global_empty()) {
2060 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
2061 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2063 if (!I->isDeclaration()) {
2064 // Ignore special globals, such as debug info.
2065 if (getGlobalVariableClass(I))
2068 if (I->hasLocalLinkage())
2070 else if (I->hasDLLImportLinkage())
2071 Out << "__declspec(dllimport) ";
2072 else if (I->hasDLLExportLinkage())
2073 Out << "__declspec(dllexport) ";
2075 // Thread Local Storage
2076 if (I->isThreadLocal())
2079 printType(Out, I->getType()->getElementType(), false,
2081 if (I->hasLinkOnceLinkage())
2082 Out << " __attribute__((common))";
2083 else if (I->hasWeakLinkage())
2084 Out << " __ATTRIBUTE_WEAK__";
2085 else if (I->hasCommonLinkage())
2086 Out << " __ATTRIBUTE_WEAK__";
2088 if (I->hasHiddenVisibility())
2089 Out << " __HIDDEN__";
2091 // If the initializer is not null, emit the initializer. If it is null,
2092 // we try to avoid emitting large amounts of zeros. The problem with
2093 // this, however, occurs when the variable has weak linkage. In this
2094 // case, the assembler will complain about the variable being both weak
2095 // and common, so we disable this optimization.
2096 // FIXME common linkage should avoid this problem.
2097 if (!I->getInitializer()->isNullValue()) {
2099 writeOperand(I->getInitializer(), true);
2100 } else if (I->hasWeakLinkage()) {
2101 // We have to specify an initializer, but it doesn't have to be
2102 // complete. If the value is an aggregate, print out { 0 }, and let
2103 // the compiler figure out the rest of the zeros.
2105 if (isa<StructType>(I->getInitializer()->getType()) ||
2106 isa<VectorType>(I->getInitializer()->getType())) {
2108 } else if (isa<ArrayType>(I->getInitializer()->getType())) {
2109 // As with structs and vectors, but with an extra set of braces
2110 // because arrays are wrapped in structs.
2113 // Just print it out normally.
2114 writeOperand(I->getInitializer(), true);
2122 Out << "\n\n/* Function Bodies */\n";
2124 // Emit some helper functions for dealing with FCMP instruction's
2126 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2127 Out << "return X == X && Y == Y; }\n";
2128 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2129 Out << "return X != X || Y != Y; }\n";
2130 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2131 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2132 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2133 Out << "return X != Y; }\n";
2134 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2135 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2136 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2137 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2138 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2139 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2140 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2141 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2142 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2143 Out << "return X == Y ; }\n";
2144 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2145 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2146 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2147 Out << "return X < Y ; }\n";
2148 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2149 Out << "return X > Y ; }\n";
2150 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2151 Out << "return X <= Y ; }\n";
2152 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2153 Out << "return X >= Y ; }\n";
2158 /// Output all floating point constants that cannot be printed accurately...
2159 void CWriter::printFloatingPointConstants(Function &F) {
2160 // Scan the module for floating point constants. If any FP constant is used
2161 // in the function, we want to redirect it here so that we do not depend on
2162 // the precision of the printed form, unless the printed form preserves
2165 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2167 printFloatingPointConstants(*I);
2172 void CWriter::printFloatingPointConstants(const Constant *C) {
2173 // If this is a constant expression, recursively check for constant fp values.
2174 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2175 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2176 printFloatingPointConstants(CE->getOperand(i));
2180 // Otherwise, check for a FP constant that we need to print.
2181 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2183 // Do not put in FPConstantMap if safe.
2184 isFPCSafeToPrint(FPC) ||
2185 // Already printed this constant?
2186 FPConstantMap.count(FPC))
2189 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2191 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2192 double Val = FPC->getValueAPF().convertToDouble();
2193 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2194 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2195 << " = 0x" << utohexstr(i)
2196 << "ULL; /* " << Val << " */\n";
2197 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2198 float Val = FPC->getValueAPF().convertToFloat();
2199 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2201 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2202 << " = 0x" << utohexstr(i)
2203 << "U; /* " << Val << " */\n";
2204 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2205 // api needed to prevent premature destruction
2206 APInt api = FPC->getValueAPF().bitcastToAPInt();
2207 const uint64_t *p = api.getRawData();
2208 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2209 << " = { 0x" << utohexstr(p[0])
2210 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2211 << "}; /* Long double constant */\n";
2212 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2213 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2214 APInt api = FPC->getValueAPF().bitcastToAPInt();
2215 const uint64_t *p = api.getRawData();
2216 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2218 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2219 << "}; /* Long double constant */\n";
2222 llvm_unreachable("Unknown float type!");
2228 /// printSymbolTable - Run through symbol table looking for type names. If a
2229 /// type name is found, emit its declaration...
2231 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2232 Out << "/* Helper union for bitcasts */\n";
2233 Out << "typedef union {\n";
2234 Out << " unsigned int Int32;\n";
2235 Out << " unsigned long long Int64;\n";
2236 Out << " float Float;\n";
2237 Out << " double Double;\n";
2238 Out << "} llvmBitCastUnion;\n";
2240 // We are only interested in the type plane of the symbol table.
2241 TypeSymbolTable::const_iterator I = TST.begin();
2242 TypeSymbolTable::const_iterator End = TST.end();
2244 // If there are no type names, exit early.
2245 if (I == End) return;
2247 // Print out forward declarations for structure types before anything else!
2248 Out << "/* Structure forward decls */\n";
2249 for (; I != End; ++I) {
2250 std::string Name = "struct " + CBEMangle("l_"+I->first);
2251 Out << Name << ";\n";
2252 TypeNames.insert(std::make_pair(I->second, Name));
2257 // Now we can print out typedefs. Above, we guaranteed that this can only be
2258 // for struct or opaque types.
2259 Out << "/* Typedefs */\n";
2260 for (I = TST.begin(); I != End; ++I) {
2261 std::string Name = CBEMangle("l_"+I->first);
2263 printType(Out, I->second, false, Name);
2269 // Keep track of which structures have been printed so far...
2270 std::set<const Type *> StructPrinted;
2272 // Loop over all structures then push them into the stack so they are
2273 // printed in the correct order.
2275 Out << "/* Structure contents */\n";
2276 for (I = TST.begin(); I != End; ++I)
2277 if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
2278 // Only print out used types!
2279 printContainedStructs(I->second, StructPrinted);
2282 // Push the struct onto the stack and recursively push all structs
2283 // this one depends on.
2285 // TODO: Make this work properly with vector types
2287 void CWriter::printContainedStructs(const Type *Ty,
2288 std::set<const Type*> &StructPrinted) {
2289 // Don't walk through pointers.
2290 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
2292 // Print all contained types first.
2293 for (Type::subtype_iterator I = Ty->subtype_begin(),
2294 E = Ty->subtype_end(); I != E; ++I)
2295 printContainedStructs(*I, StructPrinted);
2297 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
2298 // Check to see if we have already printed this struct.
2299 if (StructPrinted.insert(Ty).second) {
2300 // Print structure type out.
2301 std::string Name = TypeNames[Ty];
2302 printType(Out, Ty, false, Name, true);
2308 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2309 /// isStructReturn - Should this function actually return a struct by-value?
2310 bool isStructReturn = F->hasStructRetAttr();
2312 if (F->hasLocalLinkage()) Out << "static ";
2313 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2314 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2315 switch (F->getCallingConv()) {
2316 case CallingConv::X86_StdCall:
2317 Out << "__attribute__((stdcall)) ";
2319 case CallingConv::X86_FastCall:
2320 Out << "__attribute__((fastcall)) ";
2326 // Loop over the arguments, printing them...
2327 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2328 const AttrListPtr &PAL = F->getAttributes();
2330 std::stringstream FunctionInnards;
2332 // Print out the name...
2333 FunctionInnards << GetValueName(F) << '(';
2335 bool PrintedArg = false;
2336 if (!F->isDeclaration()) {
2337 if (!F->arg_empty()) {
2338 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2341 // If this is a struct-return function, don't print the hidden
2342 // struct-return argument.
2343 if (isStructReturn) {
2344 assert(I != E && "Invalid struct return function!");
2349 std::string ArgName;
2350 for (; I != E; ++I) {
2351 if (PrintedArg) FunctionInnards << ", ";
2352 if (I->hasName() || !Prototype)
2353 ArgName = GetValueName(I);
2356 const Type *ArgTy = I->getType();
2357 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2358 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2359 ByValParams.insert(I);
2361 printType(FunctionInnards, ArgTy,
2362 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2369 // Loop over the arguments, printing them.
2370 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2373 // If this is a struct-return function, don't print the hidden
2374 // struct-return argument.
2375 if (isStructReturn) {
2376 assert(I != E && "Invalid struct return function!");
2381 for (; I != E; ++I) {
2382 if (PrintedArg) FunctionInnards << ", ";
2383 const Type *ArgTy = *I;
2384 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2385 assert(isa<PointerType>(ArgTy));
2386 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2388 printType(FunctionInnards, ArgTy,
2389 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2395 // Finish printing arguments... if this is a vararg function, print the ...,
2396 // unless there are no known types, in which case, we just emit ().
2398 if (FT->isVarArg() && PrintedArg) {
2399 if (PrintedArg) FunctionInnards << ", ";
2400 FunctionInnards << "..."; // Output varargs portion of signature!
2401 } else if (!FT->isVarArg() && !PrintedArg) {
2402 FunctionInnards << "void"; // ret() -> ret(void) in C.
2404 FunctionInnards << ')';
2406 // Get the return tpe for the function.
2408 if (!isStructReturn)
2409 RetTy = F->getReturnType();
2411 // If this is a struct-return function, print the struct-return type.
2412 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2415 // Print out the return type and the signature built above.
2416 printType(Out, RetTy,
2417 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2418 FunctionInnards.str());
2421 static inline bool isFPIntBitCast(const Instruction &I) {
2422 if (!isa<BitCastInst>(I))
2424 const Type *SrcTy = I.getOperand(0)->getType();
2425 const Type *DstTy = I.getType();
2426 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2427 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2430 void CWriter::printFunction(Function &F) {
2431 /// isStructReturn - Should this function actually return a struct by-value?
2432 bool isStructReturn = F.hasStructRetAttr();
2434 printFunctionSignature(&F, false);
2437 // If this is a struct return function, handle the result with magic.
2438 if (isStructReturn) {
2439 const Type *StructTy =
2440 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2442 printType(Out, StructTy, false, "StructReturn");
2443 Out << "; /* Struct return temporary */\n";
2446 printType(Out, F.arg_begin()->getType(), false,
2447 GetValueName(F.arg_begin()));
2448 Out << " = &StructReturn;\n";
2451 bool PrintedVar = false;
2453 // print local variable information for the function
2454 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2455 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2457 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2458 Out << "; /* Address-exposed local */\n";
2460 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2461 !isInlinableInst(*I)) {
2463 printType(Out, I->getType(), false, GetValueName(&*I));
2466 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2468 printType(Out, I->getType(), false,
2469 GetValueName(&*I)+"__PHI_TEMPORARY");
2474 // We need a temporary for the BitCast to use so it can pluck a value out
2475 // of a union to do the BitCast. This is separate from the need for a
2476 // variable to hold the result of the BitCast.
2477 if (isFPIntBitCast(*I)) {
2478 Out << " llvmBitCastUnion " << GetValueName(&*I)
2479 << "__BITCAST_TEMPORARY;\n";
2487 if (F.hasExternalLinkage() && F.getName() == "main")
2488 Out << " CODE_FOR_MAIN();\n";
2490 // print the basic blocks
2491 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2492 if (Loop *L = LI->getLoopFor(BB)) {
2493 if (L->getHeader() == BB && L->getParentLoop() == 0)
2496 printBasicBlock(BB);
2503 void CWriter::printLoop(Loop *L) {
2504 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2505 << "' to make GCC happy */\n";
2506 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2507 BasicBlock *BB = L->getBlocks()[i];
2508 Loop *BBLoop = LI->getLoopFor(BB);
2510 printBasicBlock(BB);
2511 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2514 Out << " } while (1); /* end of syntactic loop '"
2515 << L->getHeader()->getName() << "' */\n";
2518 void CWriter::printBasicBlock(BasicBlock *BB) {
2520 // Don't print the label for the basic block if there are no uses, or if
2521 // the only terminator use is the predecessor basic block's terminator.
2522 // We have to scan the use list because PHI nodes use basic blocks too but
2523 // do not require a label to be generated.
2525 bool NeedsLabel = false;
2526 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2527 if (isGotoCodeNecessary(*PI, BB)) {
2532 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2534 // Output all of the instructions in the basic block...
2535 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2537 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2538 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2543 writeInstComputationInline(*II);
2548 // Don't emit prefix or suffix for the terminator.
2549 visit(*BB->getTerminator());
2553 // Specific Instruction type classes... note that all of the casts are
2554 // necessary because we use the instruction classes as opaque types...
2556 void CWriter::visitReturnInst(ReturnInst &I) {
2557 // If this is a struct return function, return the temporary struct.
2558 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2560 if (isStructReturn) {
2561 Out << " return StructReturn;\n";
2565 // Don't output a void return if this is the last basic block in the function
2566 if (I.getNumOperands() == 0 &&
2567 &*--I.getParent()->getParent()->end() == I.getParent() &&
2568 !I.getParent()->size() == 1) {
2572 if (I.getNumOperands() > 1) {
2575 printType(Out, I.getParent()->getParent()->getReturnType());
2576 Out << " llvm_cbe_mrv_temp = {\n";
2577 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2579 writeOperand(I.getOperand(i));
2585 Out << " return llvm_cbe_mrv_temp;\n";
2591 if (I.getNumOperands()) {
2593 writeOperand(I.getOperand(0));
2598 void CWriter::visitSwitchInst(SwitchInst &SI) {
2601 writeOperand(SI.getOperand(0));
2602 Out << ") {\n default:\n";
2603 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2604 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2606 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2608 writeOperand(SI.getOperand(i));
2610 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2611 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2612 printBranchToBlock(SI.getParent(), Succ, 2);
2613 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2619 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2620 Out << " goto *(void*)(";
2621 writeOperand(IBI.getOperand(0));
2625 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2626 Out << " /*UNREACHABLE*/;\n";
2629 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2630 /// FIXME: This should be reenabled, but loop reordering safe!!
2633 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2634 return true; // Not the direct successor, we need a goto.
2636 //isa<SwitchInst>(From->getTerminator())
2638 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2643 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2644 BasicBlock *Successor,
2646 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2647 PHINode *PN = cast<PHINode>(I);
2648 // Now we have to do the printing.
2649 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2650 if (!isa<UndefValue>(IV)) {
2651 Out << std::string(Indent, ' ');
2652 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2654 Out << "; /* for PHI node */\n";
2659 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2661 if (isGotoCodeNecessary(CurBB, Succ)) {
2662 Out << std::string(Indent, ' ') << " goto ";
2668 // Branch instruction printing - Avoid printing out a branch to a basic block
2669 // that immediately succeeds the current one.
2671 void CWriter::visitBranchInst(BranchInst &I) {
2673 if (I.isConditional()) {
2674 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2676 writeOperand(I.getCondition());
2679 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2680 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2682 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2683 Out << " } else {\n";
2684 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2685 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2688 // First goto not necessary, assume second one is...
2690 writeOperand(I.getCondition());
2693 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2694 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2699 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2700 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2705 // PHI nodes get copied into temporary values at the end of predecessor basic
2706 // blocks. We now need to copy these temporary values into the REAL value for
2708 void CWriter::visitPHINode(PHINode &I) {
2710 Out << "__PHI_TEMPORARY";
2714 void CWriter::visitBinaryOperator(Instruction &I) {
2715 // binary instructions, shift instructions, setCond instructions.
2716 assert(!isa<PointerType>(I.getType()));
2718 // We must cast the results of binary operations which might be promoted.
2719 bool needsCast = false;
2720 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2721 (I.getType() == Type::getInt16Ty(I.getContext()))
2722 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2725 printType(Out, I.getType(), false);
2729 // If this is a negation operation, print it out as such. For FP, we don't
2730 // want to print "-0.0 - X".
2731 if (BinaryOperator::isNeg(&I)) {
2733 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2735 } else if (BinaryOperator::isFNeg(&I)) {
2737 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2739 } else if (I.getOpcode() == Instruction::FRem) {
2740 // Output a call to fmod/fmodf instead of emitting a%b
2741 if (I.getType() == Type::getFloatTy(I.getContext()))
2743 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2745 else // all 3 flavors of long double
2747 writeOperand(I.getOperand(0));
2749 writeOperand(I.getOperand(1));
2753 // Write out the cast of the instruction's value back to the proper type
2755 bool NeedsClosingParens = writeInstructionCast(I);
2757 // Certain instructions require the operand to be forced to a specific type
2758 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2759 // below for operand 1
2760 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2762 switch (I.getOpcode()) {
2763 case Instruction::Add:
2764 case Instruction::FAdd: Out << " + "; break;
2765 case Instruction::Sub:
2766 case Instruction::FSub: Out << " - "; break;
2767 case Instruction::Mul:
2768 case Instruction::FMul: Out << " * "; break;
2769 case Instruction::URem:
2770 case Instruction::SRem:
2771 case Instruction::FRem: Out << " % "; break;
2772 case Instruction::UDiv:
2773 case Instruction::SDiv:
2774 case Instruction::FDiv: Out << " / "; break;
2775 case Instruction::And: Out << " & "; break;
2776 case Instruction::Or: Out << " | "; break;
2777 case Instruction::Xor: Out << " ^ "; break;
2778 case Instruction::Shl : Out << " << "; break;
2779 case Instruction::LShr:
2780 case Instruction::AShr: Out << " >> "; break;
2783 errs() << "Invalid operator type!" << I;
2785 llvm_unreachable(0);
2788 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2789 if (NeedsClosingParens)
2798 void CWriter::visitICmpInst(ICmpInst &I) {
2799 // We must cast the results of icmp which might be promoted.
2800 bool needsCast = false;
2802 // Write out the cast of the instruction's value back to the proper type
2804 bool NeedsClosingParens = writeInstructionCast(I);
2806 // Certain icmp predicate require the operand to be forced to a specific type
2807 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2808 // below for operand 1
2809 writeOperandWithCast(I.getOperand(0), I);
2811 switch (I.getPredicate()) {
2812 case ICmpInst::ICMP_EQ: Out << " == "; break;
2813 case ICmpInst::ICMP_NE: Out << " != "; break;
2814 case ICmpInst::ICMP_ULE:
2815 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2816 case ICmpInst::ICMP_UGE:
2817 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2818 case ICmpInst::ICMP_ULT:
2819 case ICmpInst::ICMP_SLT: Out << " < "; break;
2820 case ICmpInst::ICMP_UGT:
2821 case ICmpInst::ICMP_SGT: Out << " > "; break;
2824 errs() << "Invalid icmp predicate!" << I;
2826 llvm_unreachable(0);
2829 writeOperandWithCast(I.getOperand(1), I);
2830 if (NeedsClosingParens)
2838 void CWriter::visitFCmpInst(FCmpInst &I) {
2839 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2843 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2849 switch (I.getPredicate()) {
2850 default: llvm_unreachable("Illegal FCmp predicate");
2851 case FCmpInst::FCMP_ORD: op = "ord"; break;
2852 case FCmpInst::FCMP_UNO: op = "uno"; break;
2853 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2854 case FCmpInst::FCMP_UNE: op = "une"; break;
2855 case FCmpInst::FCMP_ULT: op = "ult"; break;
2856 case FCmpInst::FCMP_ULE: op = "ule"; break;
2857 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2858 case FCmpInst::FCMP_UGE: op = "uge"; break;
2859 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2860 case FCmpInst::FCMP_ONE: op = "one"; break;
2861 case FCmpInst::FCMP_OLT: op = "olt"; break;
2862 case FCmpInst::FCMP_OLE: op = "ole"; break;
2863 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2864 case FCmpInst::FCMP_OGE: op = "oge"; break;
2867 Out << "llvm_fcmp_" << op << "(";
2868 // Write the first operand
2869 writeOperand(I.getOperand(0));
2871 // Write the second operand
2872 writeOperand(I.getOperand(1));
2876 static const char * getFloatBitCastField(const Type *Ty) {
2877 switch (Ty->getTypeID()) {
2878 default: llvm_unreachable("Invalid Type");
2879 case Type::FloatTyID: return "Float";
2880 case Type::DoubleTyID: return "Double";
2881 case Type::IntegerTyID: {
2882 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2891 void CWriter::visitCastInst(CastInst &I) {
2892 const Type *DstTy = I.getType();
2893 const Type *SrcTy = I.getOperand(0)->getType();
2894 if (isFPIntBitCast(I)) {
2896 // These int<->float and long<->double casts need to be handled specially
2897 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2898 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2899 writeOperand(I.getOperand(0));
2900 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2901 << getFloatBitCastField(I.getType());
2907 printCast(I.getOpcode(), SrcTy, DstTy);
2909 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2910 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2911 I.getOpcode() == Instruction::SExt)
2914 writeOperand(I.getOperand(0));
2916 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2917 (I.getOpcode() == Instruction::Trunc ||
2918 I.getOpcode() == Instruction::FPToUI ||
2919 I.getOpcode() == Instruction::FPToSI ||
2920 I.getOpcode() == Instruction::PtrToInt)) {
2921 // Make sure we really get a trunc to bool by anding the operand with 1
2927 void CWriter::visitSelectInst(SelectInst &I) {
2929 writeOperand(I.getCondition());
2931 writeOperand(I.getTrueValue());
2933 writeOperand(I.getFalseValue());
2938 void CWriter::lowerIntrinsics(Function &F) {
2939 // This is used to keep track of intrinsics that get generated to a lowered
2940 // function. We must generate the prototypes before the function body which
2941 // will only be expanded on first use (by the loop below).
2942 std::vector<Function*> prototypesToGen;
2944 // Examine all the instructions in this function to find the intrinsics that
2945 // need to be lowered.
2946 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2947 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2948 if (CallInst *CI = dyn_cast<CallInst>(I++))
2949 if (Function *F = CI->getCalledFunction())
2950 switch (F->getIntrinsicID()) {
2951 case Intrinsic::not_intrinsic:
2952 case Intrinsic::memory_barrier:
2953 case Intrinsic::vastart:
2954 case Intrinsic::vacopy:
2955 case Intrinsic::vaend:
2956 case Intrinsic::returnaddress:
2957 case Intrinsic::frameaddress:
2958 case Intrinsic::setjmp:
2959 case Intrinsic::longjmp:
2960 case Intrinsic::prefetch:
2961 case Intrinsic::powi:
2962 case Intrinsic::x86_sse_cmp_ss:
2963 case Intrinsic::x86_sse_cmp_ps:
2964 case Intrinsic::x86_sse2_cmp_sd:
2965 case Intrinsic::x86_sse2_cmp_pd:
2966 case Intrinsic::ppc_altivec_lvsl:
2967 // We directly implement these intrinsics
2970 // If this is an intrinsic that directly corresponds to a GCC
2971 // builtin, we handle it.
2972 const char *BuiltinName = "";
2973 #define GET_GCC_BUILTIN_NAME
2974 #include "llvm/Intrinsics.gen"
2975 #undef GET_GCC_BUILTIN_NAME
2976 // If we handle it, don't lower it.
2977 if (BuiltinName[0]) break;
2979 // All other intrinsic calls we must lower.
2980 Instruction *Before = 0;
2981 if (CI != &BB->front())
2982 Before = prior(BasicBlock::iterator(CI));
2984 IL->LowerIntrinsicCall(CI);
2985 if (Before) { // Move iterator to instruction after call
2990 // If the intrinsic got lowered to another call, and that call has
2991 // a definition then we need to make sure its prototype is emitted
2992 // before any calls to it.
2993 if (CallInst *Call = dyn_cast<CallInst>(I))
2994 if (Function *NewF = Call->getCalledFunction())
2995 if (!NewF->isDeclaration())
2996 prototypesToGen.push_back(NewF);
3001 // We may have collected some prototypes to emit in the loop above.
3002 // Emit them now, before the function that uses them is emitted. But,
3003 // be careful not to emit them twice.
3004 std::vector<Function*>::iterator I = prototypesToGen.begin();
3005 std::vector<Function*>::iterator E = prototypesToGen.end();
3006 for ( ; I != E; ++I) {
3007 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
3009 printFunctionSignature(*I, true);
3015 void CWriter::visitCallInst(CallInst &I) {
3016 if (isa<InlineAsm>(I.getOperand(0)))
3017 return visitInlineAsm(I);
3019 bool WroteCallee = false;
3021 // Handle intrinsic function calls first...
3022 if (Function *F = I.getCalledFunction())
3023 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3024 if (visitBuiltinCall(I, ID, WroteCallee))
3027 Value *Callee = I.getCalledValue();
3029 const PointerType *PTy = cast<PointerType>(Callee->getType());
3030 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3032 // If this is a call to a struct-return function, assign to the first
3033 // parameter instead of passing it to the call.
3034 const AttrListPtr &PAL = I.getAttributes();
3035 bool hasByVal = I.hasByValArgument();
3036 bool isStructRet = I.hasStructRetAttr();
3038 writeOperandDeref(I.getOperand(1));
3042 if (I.isTailCall()) Out << " /*tail*/ ";
3045 // If this is an indirect call to a struct return function, we need to cast
3046 // the pointer. Ditto for indirect calls with byval arguments.
3047 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
3049 // GCC is a real PITA. It does not permit codegening casts of functions to
3050 // function pointers if they are in a call (it generates a trap instruction
3051 // instead!). We work around this by inserting a cast to void* in between
3052 // the function and the function pointer cast. Unfortunately, we can't just
3053 // form the constant expression here, because the folder will immediately
3056 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3057 // that void* and function pointers have the same size. :( To deal with this
3058 // in the common case, we handle casts where the number of arguments passed
3061 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3063 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3069 // Ok, just cast the pointer type.
3072 printStructReturnPointerFunctionType(Out, PAL,
3073 cast<PointerType>(I.getCalledValue()->getType()));
3075 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3077 printType(Out, I.getCalledValue()->getType());
3080 writeOperand(Callee);
3081 if (NeedsCast) Out << ')';
3086 unsigned NumDeclaredParams = FTy->getNumParams();
3088 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
3090 if (isStructRet) { // Skip struct return argument.
3095 bool PrintedArg = false;
3096 for (; AI != AE; ++AI, ++ArgNo) {
3097 if (PrintedArg) Out << ", ";
3098 if (ArgNo < NumDeclaredParams &&
3099 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3101 printType(Out, FTy->getParamType(ArgNo),
3102 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3105 // Check if the argument is expected to be passed by value.
3106 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3107 writeOperandDeref(*AI);
3115 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3116 /// if the entire call is handled, return false it it wasn't handled, and
3117 /// optionally set 'WroteCallee' if the callee has already been printed out.
3118 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3119 bool &WroteCallee) {
3122 // If this is an intrinsic that directly corresponds to a GCC
3123 // builtin, we emit it here.
3124 const char *BuiltinName = "";
3125 Function *F = I.getCalledFunction();
3126 #define GET_GCC_BUILTIN_NAME
3127 #include "llvm/Intrinsics.gen"
3128 #undef GET_GCC_BUILTIN_NAME
3129 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3135 case Intrinsic::memory_barrier:
3136 Out << "__sync_synchronize()";
3138 case Intrinsic::vastart:
3141 Out << "va_start(*(va_list*)";
3142 writeOperand(I.getOperand(1));
3144 // Output the last argument to the enclosing function.
3145 if (I.getParent()->getParent()->arg_empty()) {
3147 raw_string_ostream Msg(msg);
3148 Msg << "The C backend does not currently support zero "
3149 << "argument varargs functions, such as '"
3150 << I.getParent()->getParent()->getName() << "'!";
3151 llvm_report_error(Msg.str());
3153 writeOperand(--I.getParent()->getParent()->arg_end());
3156 case Intrinsic::vaend:
3157 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
3158 Out << "0; va_end(*(va_list*)";
3159 writeOperand(I.getOperand(1));
3162 Out << "va_end(*(va_list*)0)";
3165 case Intrinsic::vacopy:
3167 Out << "va_copy(*(va_list*)";
3168 writeOperand(I.getOperand(1));
3169 Out << ", *(va_list*)";
3170 writeOperand(I.getOperand(2));
3173 case Intrinsic::returnaddress:
3174 Out << "__builtin_return_address(";
3175 writeOperand(I.getOperand(1));
3178 case Intrinsic::frameaddress:
3179 Out << "__builtin_frame_address(";
3180 writeOperand(I.getOperand(1));
3183 case Intrinsic::powi:
3184 Out << "__builtin_powi(";
3185 writeOperand(I.getOperand(1));
3187 writeOperand(I.getOperand(2));
3190 case Intrinsic::setjmp:
3191 Out << "setjmp(*(jmp_buf*)";
3192 writeOperand(I.getOperand(1));
3195 case Intrinsic::longjmp:
3196 Out << "longjmp(*(jmp_buf*)";
3197 writeOperand(I.getOperand(1));
3199 writeOperand(I.getOperand(2));
3202 case Intrinsic::prefetch:
3203 Out << "LLVM_PREFETCH((const void *)";
3204 writeOperand(I.getOperand(1));
3206 writeOperand(I.getOperand(2));
3208 writeOperand(I.getOperand(3));
3211 case Intrinsic::stacksave:
3212 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3213 // to work around GCC bugs (see PR1809).
3214 Out << "0; *((void**)&" << GetValueName(&I)
3215 << ") = __builtin_stack_save()";
3217 case Intrinsic::x86_sse_cmp_ss:
3218 case Intrinsic::x86_sse_cmp_ps:
3219 case Intrinsic::x86_sse2_cmp_sd:
3220 case Intrinsic::x86_sse2_cmp_pd:
3222 printType(Out, I.getType());
3224 // Multiple GCC builtins multiplex onto this intrinsic.
3225 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3226 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3227 case 0: Out << "__builtin_ia32_cmpeq"; break;
3228 case 1: Out << "__builtin_ia32_cmplt"; break;
3229 case 2: Out << "__builtin_ia32_cmple"; break;
3230 case 3: Out << "__builtin_ia32_cmpunord"; break;
3231 case 4: Out << "__builtin_ia32_cmpneq"; break;
3232 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3233 case 6: Out << "__builtin_ia32_cmpnle"; break;
3234 case 7: Out << "__builtin_ia32_cmpord"; break;
3236 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3240 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3246 writeOperand(I.getOperand(1));
3248 writeOperand(I.getOperand(2));
3251 case Intrinsic::ppc_altivec_lvsl:
3253 printType(Out, I.getType());
3255 Out << "__builtin_altivec_lvsl(0, (void*)";
3256 writeOperand(I.getOperand(1));
3262 //This converts the llvm constraint string to something gcc is expecting.
3263 //TODO: work out platform independent constraints and factor those out
3264 // of the per target tables
3265 // handle multiple constraint codes
3266 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3267 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3269 // Grab the translation table from MCAsmInfo if it exists.
3270 const MCAsmInfo *TargetAsm;
3271 std::string Triple = TheModule->getTargetTriple();
3273 Triple = llvm::sys::getHostTriple();
3276 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3277 TargetAsm = Match->createAsmInfo(Triple);
3281 const char *const *table = TargetAsm->getAsmCBE();
3283 // Search the translation table if it exists.
3284 for (int i = 0; table && table[i]; i += 2)
3285 if (c.Codes[0] == table[i]) {
3290 // Default is identity.
3295 //TODO: import logic from AsmPrinter.cpp
3296 static std::string gccifyAsm(std::string asmstr) {
3297 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3298 if (asmstr[i] == '\n')
3299 asmstr.replace(i, 1, "\\n");
3300 else if (asmstr[i] == '\t')
3301 asmstr.replace(i, 1, "\\t");
3302 else if (asmstr[i] == '$') {
3303 if (asmstr[i + 1] == '{') {
3304 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3305 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3306 std::string n = "%" +
3307 asmstr.substr(a + 1, b - a - 1) +
3308 asmstr.substr(i + 2, a - i - 2);
3309 asmstr.replace(i, b - i + 1, n);
3312 asmstr.replace(i, 1, "%");
3314 else if (asmstr[i] == '%')//grr
3315 { asmstr.replace(i, 1, "%%"); ++i;}
3320 //TODO: assumptions about what consume arguments from the call are likely wrong
3321 // handle communitivity
3322 void CWriter::visitInlineAsm(CallInst &CI) {
3323 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3324 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3326 std::vector<std::pair<Value*, int> > ResultVals;
3327 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3329 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3330 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3331 ResultVals.push_back(std::make_pair(&CI, (int)i));
3333 ResultVals.push_back(std::make_pair(&CI, -1));
3336 // Fix up the asm string for gcc and emit it.
3337 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3340 unsigned ValueCount = 0;
3341 bool IsFirst = true;
3343 // Convert over all the output constraints.
3344 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3345 E = Constraints.end(); I != E; ++I) {
3347 if (I->Type != InlineAsm::isOutput) {
3349 continue; // Ignore non-output constraints.
3352 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3353 std::string C = InterpretASMConstraint(*I);
3354 if (C.empty()) continue;
3365 if (ValueCount < ResultVals.size()) {
3366 DestVal = ResultVals[ValueCount].first;
3367 DestValNo = ResultVals[ValueCount].second;
3369 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3371 if (I->isEarlyClobber)
3374 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3375 if (DestValNo != -1)
3376 Out << ".field" << DestValNo; // Multiple retvals.
3382 // Convert over all the input constraints.
3386 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3387 E = Constraints.end(); I != E; ++I) {
3388 if (I->Type != InlineAsm::isInput) {
3390 continue; // Ignore non-input constraints.
3393 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3394 std::string C = InterpretASMConstraint(*I);
3395 if (C.empty()) continue;
3402 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3403 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3405 Out << "\"" << C << "\"(";
3407 writeOperand(SrcVal);
3409 writeOperandDeref(SrcVal);
3413 // Convert over the clobber constraints.
3415 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3416 E = Constraints.end(); I != E; ++I) {
3417 if (I->Type != InlineAsm::isClobber)
3418 continue; // Ignore non-input constraints.
3420 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3421 std::string C = InterpretASMConstraint(*I);
3422 if (C.empty()) continue;
3429 Out << '\"' << C << '"';
3435 void CWriter::visitAllocaInst(AllocaInst &I) {
3437 printType(Out, I.getType());
3438 Out << ") alloca(sizeof(";
3439 printType(Out, I.getType()->getElementType());
3441 if (I.isArrayAllocation()) {
3443 writeOperand(I.getOperand(0));
3448 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3449 gep_type_iterator E, bool Static) {
3451 // If there are no indices, just print out the pointer.
3457 // Find out if the last index is into a vector. If so, we have to print this
3458 // specially. Since vectors can't have elements of indexable type, only the
3459 // last index could possibly be of a vector element.
3460 const VectorType *LastIndexIsVector = 0;
3462 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3463 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3468 // If the last index is into a vector, we can't print it as &a[i][j] because
3469 // we can't index into a vector with j in GCC. Instead, emit this as
3470 // (((float*)&a[i])+j)
3471 if (LastIndexIsVector) {
3473 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3479 // If the first index is 0 (very typical) we can do a number of
3480 // simplifications to clean up the code.
3481 Value *FirstOp = I.getOperand();
3482 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3483 // First index isn't simple, print it the hard way.
3486 ++I; // Skip the zero index.
3488 // Okay, emit the first operand. If Ptr is something that is already address
3489 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3490 if (isAddressExposed(Ptr)) {
3491 writeOperandInternal(Ptr, Static);
3492 } else if (I != E && isa<StructType>(*I)) {
3493 // If we didn't already emit the first operand, see if we can print it as
3494 // P->f instead of "P[0].f"
3496 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3497 ++I; // eat the struct index as well.
3499 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3506 for (; I != E; ++I) {
3507 if (isa<StructType>(*I)) {
3508 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3509 } else if (isa<ArrayType>(*I)) {
3511 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3513 } else if (!isa<VectorType>(*I)) {
3515 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3518 // If the last index is into a vector, then print it out as "+j)". This
3519 // works with the 'LastIndexIsVector' code above.
3520 if (isa<Constant>(I.getOperand()) &&
3521 cast<Constant>(I.getOperand())->isNullValue()) {
3522 Out << "))"; // avoid "+0".
3525 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3533 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3534 bool IsVolatile, unsigned Alignment) {
3536 bool IsUnaligned = Alignment &&
3537 Alignment < TD->getABITypeAlignment(OperandType);
3541 if (IsVolatile || IsUnaligned) {
3544 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3545 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3548 if (IsVolatile) Out << "volatile ";
3554 writeOperand(Operand);
3556 if (IsVolatile || IsUnaligned) {
3563 void CWriter::visitLoadInst(LoadInst &I) {
3564 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3569 void CWriter::visitStoreInst(StoreInst &I) {
3570 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3571 I.isVolatile(), I.getAlignment());
3573 Value *Operand = I.getOperand(0);
3574 Constant *BitMask = 0;
3575 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3576 if (!ITy->isPowerOf2ByteWidth())
3577 // We have a bit width that doesn't match an even power-of-2 byte
3578 // size. Consequently we must & the value with the type's bit mask
3579 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3582 writeOperand(Operand);
3585 printConstant(BitMask, false);
3590 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3591 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3592 gep_type_end(I), false);
3595 void CWriter::visitVAArgInst(VAArgInst &I) {
3596 Out << "va_arg(*(va_list*)";
3597 writeOperand(I.getOperand(0));
3599 printType(Out, I.getType());
3603 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3604 const Type *EltTy = I.getType()->getElementType();
3605 writeOperand(I.getOperand(0));
3608 printType(Out, PointerType::getUnqual(EltTy));
3609 Out << ")(&" << GetValueName(&I) << "))[";
3610 writeOperand(I.getOperand(2));
3612 writeOperand(I.getOperand(1));
3616 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3617 // We know that our operand is not inlined.
3620 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3621 printType(Out, PointerType::getUnqual(EltTy));
3622 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3623 writeOperand(I.getOperand(1));
3627 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3629 printType(Out, SVI.getType());
3631 const VectorType *VT = SVI.getType();
3632 unsigned NumElts = VT->getNumElements();
3633 const Type *EltTy = VT->getElementType();
3635 for (unsigned i = 0; i != NumElts; ++i) {
3637 int SrcVal = SVI.getMaskValue(i);
3638 if ((unsigned)SrcVal >= NumElts*2) {
3639 Out << " 0/*undef*/ ";
3641 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3642 if (isa<Instruction>(Op)) {
3643 // Do an extractelement of this value from the appropriate input.
3645 printType(Out, PointerType::getUnqual(EltTy));
3646 Out << ")(&" << GetValueName(Op)
3647 << "))[" << (SrcVal & (NumElts-1)) << "]";
3648 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3651 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3660 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3661 // Start by copying the entire aggregate value into the result variable.
3662 writeOperand(IVI.getOperand(0));
3665 // Then do the insert to update the field.
3666 Out << GetValueName(&IVI);
3667 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3669 const Type *IndexedTy =
3670 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3671 if (isa<ArrayType>(IndexedTy))
3672 Out << ".array[" << *i << "]";
3674 Out << ".field" << *i;
3677 writeOperand(IVI.getOperand(1));
3680 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3682 if (isa<UndefValue>(EVI.getOperand(0))) {
3684 printType(Out, EVI.getType());
3685 Out << ") 0/*UNDEF*/";
3687 Out << GetValueName(EVI.getOperand(0));
3688 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3690 const Type *IndexedTy =
3691 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3692 if (isa<ArrayType>(IndexedTy))
3693 Out << ".array[" << *i << "]";
3695 Out << ".field" << *i;
3701 //===----------------------------------------------------------------------===//
3702 // External Interface declaration
3703 //===----------------------------------------------------------------------===//
3705 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3706 formatted_raw_ostream &o,
3707 CodeGenFileType FileType,
3708 CodeGenOpt::Level OptLevel) {
3709 if (FileType != TargetMachine::AssemblyFile) return true;
3711 PM.add(createGCLoweringPass());
3712 PM.add(createLowerInvokePass());
3713 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3714 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3715 PM.add(new CWriter(o));
3716 PM.add(createGCInfoDeleter());