1 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
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 MSIL code.
12 //===----------------------------------------------------------------------===//
14 #include "MSILWriter.h"
15 #include "llvm/CallingConv.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/TypeSymbolTable.h"
20 #include "llvm/Analysis/ConstantsScanner.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/CodeGen/Passes.h"
30 // TargetMachine for the MSIL
31 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32 const TargetData DataLayout; // Calculates type size & alignment
34 MSILTarget(const Target &T, const Module &M, const std::string &FS)
35 : TargetMachine(T), DataLayout(&M) {}
37 virtual bool WantsWholeFile() const { return true; }
38 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
40 CodeGenFileType FileType,
41 CodeGenOpt::Level OptLevel);
43 // This class always works, but shouldn't be the default in most cases.
44 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
46 virtual const TargetData *getTargetData() const { return &DataLayout; }
50 static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
52 // Force static initialization.
53 extern "C" void LLVMInitializeMSILTarget() { }
55 bool MSILModule::runOnModule(Module &M) {
57 TD = &getAnalysis<TargetData>();
60 TypeSymbolTable& Table = M.getTypeSymbolTable();
61 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
62 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
63 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
66 std::set<const Type *>::iterator T = Types.find(I->second);
75 // Find unnamed types.
76 unsigned RenameCounter = 0;
77 for (std::set<const Type *>::const_iterator I = Types.begin(),
78 E = Types.end(); I!=E; ++I)
79 if (const StructType *STy = dyn_cast<StructType>(*I)) {
80 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
84 // Pointer for FunctionPass.
85 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
89 char MSILModule::ID = 0;
90 char MSILWriter::ID = 0;
92 bool MSILWriter::runOnFunction(Function &F) {
93 if (F.isDeclaration()) return false;
95 // Do not codegen any 'available_externally' functions at all, they have
96 // definitions outside the translation unit.
97 if (F.hasAvailableExternallyLinkage())
100 LInfo = &getAnalysis<LoopInfo>();
106 bool MSILWriter::doInitialization(Module &M) {
108 Mang = new Mangler(M);
109 Out << ".assembly extern mscorlib {}\n";
110 Out << ".assembly MSIL {}\n\n";
111 Out << "// External\n";
113 Out << "// Declarations\n";
114 printDeclarations(M.getTypeSymbolTable());
115 Out << "// Definitions\n";
116 printGlobalVariables();
117 Out << "// Startup code\n";
118 printModuleStartup();
123 bool MSILWriter::doFinalization(Module &M) {
129 void MSILWriter::printModuleStartup() {
131 ".method static public int32 $MSIL_Startup() {\n"
133 "\t.locals (native int i)\n"
134 "\t.locals (native int argc)\n"
135 "\t.locals (native int ptr)\n"
136 "\t.locals (void* argv)\n"
137 "\t.locals (string[] args)\n"
138 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
145 printPtrLoad(TD->getPointerSize());
160 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
161 "StringToHGlobalAnsi(string)\n"
165 printPtrLoad(TD->getPointerSize());
177 "\tcall void $MSIL_Init()\n";
179 // Call user 'main' function.
180 const Function* F = ModulePtr->getFunction("main");
181 if (!F || F->isDeclaration()) {
182 Out << "\tldc.i4.0\n\tret\n}\n";
186 std::string Args("");
187 Function::const_arg_iterator Arg1,Arg2;
189 switch (F->arg_size()) {
194 Arg1 = F->arg_begin();
195 if (Arg1->getType()->isInteger()) {
196 Out << "\tldloc\targc\n";
197 Args = getTypeName(Arg1->getType());
202 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
203 if (Arg1->getType()->isInteger() &&
204 Arg2->getType()->getTypeID() == Type::PointerTyID) {
205 Out << "\tldloc\targc\n\tldloc\targv\n";
206 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
214 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
215 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
216 Out << "\tldc.i4.0\n";
218 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
219 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
221 Out << "\tldc.i4.0\n";
223 Out << "\tconv.i4\n";
228 bool MSILWriter::isZeroValue(const Value* V) {
229 if (const Constant *C = dyn_cast<Constant>(V))
230 return C->isNullValue();
235 std::string MSILWriter::getValueName(const Value* V) {
237 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
238 Name = Mang->getMangledName(GV);
240 unsigned &No = AnonValueNumbers[V];
241 if (No == 0) No = ++NextAnonValueNumber;
242 Name = "tmp" + utostr(No);
245 // Name into the quotes allow control and space characters.
250 std::string MSILWriter::getLabelName(const std::string& Name) {
251 if (Name.find('.')!=std::string::npos) {
252 std::string Tmp(Name);
253 // Replace unaccepable characters in the label name.
254 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
255 if (*I=='.') *I = '@';
262 std::string MSILWriter::getLabelName(const Value* V) {
264 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
265 Name = Mang->getMangledName(GV);
267 unsigned &No = AnonValueNumbers[V];
268 if (No == 0) No = ++NextAnonValueNumber;
269 Name = "tmp" + utostr(No);
272 return getLabelName(Name);
276 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
277 switch (CallingConvID) {
279 case CallingConv::Cold:
280 case CallingConv::Fast:
281 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
282 case CallingConv::X86_FastCall:
283 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
284 case CallingConv::X86_StdCall:
285 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
287 cerr << "CallingConvID = " << CallingConvID << '\n';
288 llvm_unreachable("Unsupported calling convention");
290 return ""; // Not reached
294 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
295 std::string Tmp = "";
296 const Type* ElemTy = Ty;
297 assert(Ty->getTypeID()==TyID && "Invalid type passed");
298 // Walk trought array element types.
300 // Multidimensional array.
301 if (ElemTy->getTypeID()==TyID) {
302 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
303 Tmp += utostr(ATy->getNumElements());
304 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
305 Tmp += utostr(VTy->getNumElements());
306 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
308 // Base element type found.
309 if (ElemTy->getTypeID()!=TyID) break;
312 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
316 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
317 unsigned NumBits = 0;
318 switch (Ty->getTypeID()) {
321 case Type::IntegerTyID:
322 NumBits = getBitWidth(Ty);
326 return "unsigned int"+utostr(NumBits)+" ";
327 return "int"+utostr(NumBits)+" ";
328 case Type::FloatTyID:
330 case Type::DoubleTyID:
333 cerr << "Type = " << *Ty << '\n';
334 llvm_unreachable("Invalid primitive type");
336 return ""; // Not reached
340 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
342 if (Ty->isPrimitiveType() || Ty->isInteger())
343 return getPrimitiveTypeName(Ty,isSigned);
344 // FIXME: "OpaqueType" support
345 switch (Ty->getTypeID()) {
346 case Type::PointerTyID:
348 case Type::StructTyID:
350 return ModulePtr->getTypeName(Ty);
351 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
352 case Type::ArrayTyID:
354 return getArrayTypeName(Ty->getTypeID(),Ty);
355 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
356 case Type::VectorTyID:
358 return getArrayTypeName(Ty->getTypeID(),Ty);
359 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
361 cerr << "Type = " << *Ty << '\n';
362 llvm_unreachable("Invalid type in getTypeName()");
364 return ""; // Not reached
368 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
370 if (isa<Argument>(V))
373 else if (const Function* F = dyn_cast<Function>(V))
374 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
376 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
377 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
379 else if (isa<Constant>(V))
380 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
386 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
388 unsigned NumBits = 0;
389 switch (Ty->getTypeID()) {
390 // Integer constant, expanding for stack operations.
391 case Type::IntegerTyID:
392 NumBits = getBitWidth(Ty);
393 // Expand integer value to "int32" or "int64".
394 if (Expand) return (NumBits<=32 ? "i4" : "i8");
395 if (NumBits==1) return "i1";
396 return (isSigned ? "i" : "u")+utostr(NumBits/8);
398 case Type::FloatTyID:
400 case Type::DoubleTyID:
402 case Type::PointerTyID:
403 return "i"+utostr(TD->getTypeAllocSize(Ty));
405 cerr << "TypeID = " << Ty->getTypeID() << '\n';
406 llvm_unreachable("Invalid type in TypeToPostfix()");
408 return ""; // Not reached
412 void MSILWriter::printConvToPtr() {
413 switch (ModulePtr->getPointerSize()) {
414 case Module::Pointer32:
415 printSimpleInstruction("conv.u4");
417 case Module::Pointer64:
418 printSimpleInstruction("conv.u8");
421 llvm_unreachable("Module use not supporting pointer size");
426 void MSILWriter::printPtrLoad(uint64_t N) {
427 switch (ModulePtr->getPointerSize()) {
428 case Module::Pointer32:
429 printSimpleInstruction("ldc.i4",utostr(N).c_str());
430 // FIXME: Need overflow test?
432 cerr << "Value = " << utostr(N) << '\n';
433 llvm_unreachable("32-bit pointer overflowed");
436 case Module::Pointer64:
437 printSimpleInstruction("ldc.i8",utostr(N).c_str());
440 llvm_unreachable("Module use not supporting pointer size");
445 void MSILWriter::printValuePtrLoad(const Value* V) {
451 void MSILWriter::printConstLoad(const Constant* C) {
452 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
454 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
455 if (CInt->isMinValue(true))
456 Out << CInt->getSExtValue();
458 Out << CInt->getZExtValue();
459 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
463 if (FP->getType()->getTypeID()==Type::FloatTyID) {
464 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
467 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
470 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
471 } else if (isa<UndefValue>(C)) {
472 // Undefined constant value = NULL.
475 cerr << "Constant = " << *C << '\n';
476 llvm_unreachable("Invalid constant value");
482 void MSILWriter::printValueLoad(const Value* V) {
483 MSILWriter::ValueType Location = getValueLocation(V);
485 // Global variable or function address.
488 if (const Function* F = dyn_cast<Function>(V)) {
489 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
490 printSimpleInstruction("ldftn",
491 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
494 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
495 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
496 Tmp = "void* "+getValueName(V);
497 printSimpleInstruction("ldsfld",Tmp.c_str());
499 Tmp = getTypeName(ElemTy)+getValueName(V);
500 printSimpleInstruction("ldsflda",Tmp.c_str());
504 // Function argument.
506 printSimpleInstruction("ldarg",getValueName(V).c_str());
508 // Local function variable.
510 printSimpleInstruction("ldloc",getValueName(V).c_str());
514 if (isa<ConstantPointerNull>(V))
517 printConstLoad(cast<Constant>(V));
519 // Constant expression.
521 printConstantExpr(cast<ConstantExpr>(V));
524 cerr << "Value = " << *V << '\n';
525 llvm_unreachable("Invalid value location");
530 void MSILWriter::printValueSave(const Value* V) {
531 switch (getValueLocation(V)) {
533 printSimpleInstruction("starg",getValueName(V).c_str());
536 printSimpleInstruction("stloc",getValueName(V).c_str());
539 cerr << "Value = " << *V << '\n';
540 llvm_unreachable("Invalid value location");
545 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
546 const Value* Right) {
547 printValueLoad(Left);
548 printValueLoad(Right);
549 Out << '\t' << Name << '\n';
553 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
555 Out << '\t' << Inst << '\t' << Operand << '\n';
557 Out << '\t' << Inst << '\n';
561 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
562 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
563 isa<PHINode>(I); ++I) {
564 const PHINode* Phi = cast<PHINode>(I);
565 const Value* Val = Phi->getIncomingValueForBlock(Src);
566 if (isa<UndefValue>(Val)) continue;
573 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
574 const BasicBlock* TrueBB,
575 const BasicBlock* FalseBB) {
576 if (TrueBB==FalseBB) {
577 // "TrueBB" and "FalseBB" destination equals
578 printPHICopy(CurrBB,TrueBB);
579 printSimpleInstruction("pop");
580 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
581 } else if (FalseBB==NULL) {
582 // If "FalseBB" not used the jump have condition
583 printPHICopy(CurrBB,TrueBB);
584 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
585 } else if (TrueBB==NULL) {
586 // If "TrueBB" not used the jump is unconditional
587 printPHICopy(CurrBB,FalseBB);
588 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
590 // Copy PHI instructions for each block
591 std::string TmpLabel;
592 // Print PHI instructions for "TrueBB"
593 if (isa<PHINode>(TrueBB->begin())) {
594 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
595 printSimpleInstruction("brtrue",TmpLabel.c_str());
597 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
599 // Print PHI instructions for "FalseBB"
600 if (isa<PHINode>(FalseBB->begin())) {
601 printPHICopy(CurrBB,FalseBB);
602 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
604 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
606 if (isa<PHINode>(TrueBB->begin())) {
607 // Handle "TrueBB" PHI Copy
608 Out << TmpLabel << ":\n";
609 printPHICopy(CurrBB,TrueBB);
610 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
616 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
617 if (Inst->isUnconditional()) {
618 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
620 printValueLoad(Inst->getCondition());
621 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
622 Inst->getSuccessor(1));
627 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
628 const Value* VFalse) {
629 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
630 printValueLoad(VTrue);
631 printValueLoad(Cond);
632 printSimpleInstruction("brtrue",TmpLabel.c_str());
633 printSimpleInstruction("pop");
634 printValueLoad(VFalse);
635 Out << TmpLabel << ":\n";
639 void MSILWriter::printIndirectLoad(const Value* V) {
640 const Type* Ty = V->getType();
642 if (const PointerType* P = dyn_cast<PointerType>(Ty))
643 Ty = P->getElementType();
644 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
645 printSimpleInstruction(Tmp.c_str());
649 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
652 printIndirectSave(Val->getType());
656 void MSILWriter::printIndirectSave(const Type* Ty) {
657 // Instruction need signed postfix for any type.
658 std::string postfix = getTypePostfix(Ty, false);
659 if (*postfix.begin()=='u') *postfix.begin() = 'i';
660 postfix = "stind."+postfix;
661 printSimpleInstruction(postfix.c_str());
665 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
666 const Type* Ty, const Type* SrcTy) {
671 case Instruction::SExt:
672 // If sign extending int, convert first from unsigned to signed
673 // with the same bit size - because otherwise we will loose the sign.
675 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
676 printSimpleInstruction(Tmp.c_str());
679 case Instruction::SIToFP:
680 case Instruction::FPToSI:
681 Tmp = "conv."+getTypePostfix(Ty,false,true);
682 printSimpleInstruction(Tmp.c_str());
685 case Instruction::FPTrunc:
686 case Instruction::FPExt:
687 case Instruction::UIToFP:
688 case Instruction::Trunc:
689 case Instruction::ZExt:
690 case Instruction::FPToUI:
691 case Instruction::PtrToInt:
692 case Instruction::IntToPtr:
693 Tmp = "conv."+getTypePostfix(Ty,false);
694 printSimpleInstruction(Tmp.c_str());
697 case Instruction::BitCast:
698 // FIXME: meaning that ld*/st* instruction do not change data format.
701 cerr << "Opcode = " << Op << '\n';
702 llvm_unreachable("Invalid conversion instruction");
707 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
708 gep_type_iterator E) {
711 printValuePtrLoad(V);
712 // Calculate element offset.
715 const Value* IndexValue = I.getOperand();
716 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
717 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
718 // Offset is the sum of all previous structure fields.
719 for (uint64_t F = 0; F<FieldIndex; ++F)
720 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
722 printSimpleInstruction("add");
724 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
725 Size = TD->getTypeAllocSize(SeqTy->getElementType());
727 Size = TD->getTypeAllocSize(*I);
729 // Add offset of current element to stack top.
730 if (!isZeroValue(IndexValue)) {
731 // Constant optimization.
732 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
733 if (C->getValue().isNegative()) {
734 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
735 printSimpleInstruction("sub");
738 printPtrLoad(C->getZExtValue()*Size);
741 printValuePtrLoad(IndexValue);
742 printSimpleInstruction("mul");
744 printSimpleInstruction("add");
750 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
751 const Instruction* Inst,
754 if (Ty->isVarArg()) Tmp += "vararg ";
755 // Name and return type.
756 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
757 // Function argument type list.
758 unsigned NumParams = Ty->getNumParams();
759 for (unsigned I = 0; I!=NumParams; ++I) {
760 if (I!=0) Tmp += ",";
761 Tmp += getTypeName(Ty->getParamType(I));
763 // CLR needs to know the exact amount of parameters received by vararg
764 // function, because caller cleans the stack.
765 if (Ty->isVarArg() && Inst) {
766 // Origin to function arguments in "CallInst" or "InvokeInst".
767 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
768 // Print variable argument types.
769 unsigned NumOperands = Inst->getNumOperands()-Org;
770 if (NumParams<NumOperands) {
771 if (NumParams!=0) Tmp += ", ";
773 for (unsigned J = NumParams; J!=NumOperands; ++J) {
774 if (J!=NumParams) Tmp += ", ";
775 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
783 void MSILWriter::printFunctionCall(const Value* FnVal,
784 const Instruction* Inst) {
785 // Get function calling convention.
786 std::string Name = "";
787 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
788 Name = getConvModopt(Call->getCallingConv());
789 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
790 Name = getConvModopt(Invoke->getCallingConv());
792 cerr << "Instruction = " << Inst->getName() << '\n';
793 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
795 if (const Function* F = dyn_cast<Function>(FnVal)) {
797 Name += getValueName(F);
798 printSimpleInstruction("call",
799 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
801 // Indirect function call.
802 const PointerType* PTy = cast<PointerType>(FnVal->getType());
803 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
804 // Load function address.
805 printValueLoad(FnVal);
806 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
811 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
813 switch (Inst->getIntrinsicID()) {
814 case Intrinsic::vastart:
815 Name = getValueName(Inst->getOperand(1));
816 Name.insert(Name.length()-1,"$valist");
817 // Obtain the argument handle.
818 printSimpleInstruction("ldloca",Name.c_str());
819 printSimpleInstruction("arglist");
820 printSimpleInstruction("call",
821 "instance void [mscorlib]System.ArgIterator::.ctor"
822 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
823 // Save as pointer type "void*"
824 printValueLoad(Inst->getOperand(1));
825 printSimpleInstruction("ldloca",Name.c_str());
826 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
828 case Intrinsic::vaend:
829 // Close argument list handle.
830 printIndirectLoad(Inst->getOperand(1));
831 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
833 case Intrinsic::vacopy:
834 // Copy "ArgIterator" valuetype.
835 printIndirectLoad(Inst->getOperand(1));
836 printIndirectLoad(Inst->getOperand(2));
837 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
840 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
841 llvm_unreachable("Invalid intrinsic function");
846 void MSILWriter::printCallInstruction(const Instruction* Inst) {
847 if (isa<IntrinsicInst>(Inst)) {
848 // Handle intrinsic function.
849 printIntrinsicCall(cast<IntrinsicInst>(Inst));
851 // Load arguments to stack and call function.
852 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
853 printValueLoad(Inst->getOperand(I));
854 printFunctionCall(Inst->getOperand(0),Inst);
859 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
860 const Value* Right) {
862 case ICmpInst::ICMP_EQ:
863 printBinaryInstruction("ceq",Left,Right);
865 case ICmpInst::ICMP_NE:
866 // Emulate = not neg (Op1 eq Op2)
867 printBinaryInstruction("ceq",Left,Right);
868 printSimpleInstruction("neg");
869 printSimpleInstruction("not");
871 case ICmpInst::ICMP_ULE:
872 case ICmpInst::ICMP_SLE:
873 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
874 printBinaryInstruction("ceq",Left,Right);
875 if (Predicate==ICmpInst::ICMP_ULE)
876 printBinaryInstruction("clt.un",Left,Right);
878 printBinaryInstruction("clt",Left,Right);
879 printSimpleInstruction("or");
881 case ICmpInst::ICMP_UGE:
882 case ICmpInst::ICMP_SGE:
883 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
884 printBinaryInstruction("ceq",Left,Right);
885 if (Predicate==ICmpInst::ICMP_UGE)
886 printBinaryInstruction("cgt.un",Left,Right);
888 printBinaryInstruction("cgt",Left,Right);
889 printSimpleInstruction("or");
891 case ICmpInst::ICMP_ULT:
892 printBinaryInstruction("clt.un",Left,Right);
894 case ICmpInst::ICMP_SLT:
895 printBinaryInstruction("clt",Left,Right);
897 case ICmpInst::ICMP_UGT:
898 printBinaryInstruction("cgt.un",Left,Right);
900 case ICmpInst::ICMP_SGT:
901 printBinaryInstruction("cgt",Left,Right);
904 cerr << "Predicate = " << Predicate << '\n';
905 llvm_unreachable("Invalid icmp predicate");
910 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
911 const Value* Right) {
912 // FIXME: Correct comparison
913 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
915 case FCmpInst::FCMP_UGT:
916 // X > Y || llvm_fcmp_uno(X, Y)
917 printBinaryInstruction("cgt",Left,Right);
918 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
919 printSimpleInstruction("or");
921 case FCmpInst::FCMP_OGT:
923 printBinaryInstruction("cgt",Left,Right);
925 case FCmpInst::FCMP_UGE:
926 // X >= Y || llvm_fcmp_uno(X, Y)
927 printBinaryInstruction("ceq",Left,Right);
928 printBinaryInstruction("cgt",Left,Right);
929 printSimpleInstruction("or");
930 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
931 printSimpleInstruction("or");
933 case FCmpInst::FCMP_OGE:
935 printBinaryInstruction("ceq",Left,Right);
936 printBinaryInstruction("cgt",Left,Right);
937 printSimpleInstruction("or");
939 case FCmpInst::FCMP_ULT:
940 // X < Y || llvm_fcmp_uno(X, Y)
941 printBinaryInstruction("clt",Left,Right);
942 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
943 printSimpleInstruction("or");
945 case FCmpInst::FCMP_OLT:
947 printBinaryInstruction("clt",Left,Right);
949 case FCmpInst::FCMP_ULE:
950 // X <= Y || llvm_fcmp_uno(X, Y)
951 printBinaryInstruction("ceq",Left,Right);
952 printBinaryInstruction("clt",Left,Right);
953 printSimpleInstruction("or");
954 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
955 printSimpleInstruction("or");
957 case FCmpInst::FCMP_OLE:
959 printBinaryInstruction("ceq",Left,Right);
960 printBinaryInstruction("clt",Left,Right);
961 printSimpleInstruction("or");
963 case FCmpInst::FCMP_UEQ:
964 // X == Y || llvm_fcmp_uno(X, Y)
965 printBinaryInstruction("ceq",Left,Right);
966 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
967 printSimpleInstruction("or");
969 case FCmpInst::FCMP_OEQ:
971 printBinaryInstruction("ceq",Left,Right);
973 case FCmpInst::FCMP_UNE:
975 printBinaryInstruction("ceq",Left,Right);
976 printSimpleInstruction("neg");
977 printSimpleInstruction("not");
979 case FCmpInst::FCMP_ONE:
980 // X != Y && llvm_fcmp_ord(X, Y)
981 printBinaryInstruction("ceq",Left,Right);
982 printSimpleInstruction("not");
984 case FCmpInst::FCMP_ORD:
985 // return X == X && Y == Y
986 printBinaryInstruction("ceq",Left,Left);
987 printBinaryInstruction("ceq",Right,Right);
988 printSimpleInstruction("or");
990 case FCmpInst::FCMP_UNO:
992 printBinaryInstruction("ceq",Left,Left);
993 printSimpleInstruction("not");
994 printBinaryInstruction("ceq",Right,Right);
995 printSimpleInstruction("not");
996 printSimpleInstruction("or");
999 llvm_unreachable("Illegal FCmp predicate");
1004 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1005 std::string Label = "leave$normal_"+utostr(getUniqID());
1008 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1009 printValueLoad(Inst->getOperand(I));
1010 // Print call instruction
1011 printFunctionCall(Inst->getOperand(0),Inst);
1012 // Save function result and leave "try" block
1013 printValueSave(Inst);
1014 printSimpleInstruction("leave",Label.c_str());
1016 Out << "catch [mscorlib]System.Exception {\n";
1017 // Redirect to unwind block
1018 printSimpleInstruction("pop");
1019 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1020 Out << "}\n" << Label << ":\n";
1021 // Redirect to continue block
1022 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1026 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1027 // FIXME: Emulate with IL "switch" instruction
1028 // Emulate = if () else if () else if () else ...
1029 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1030 printValueLoad(Inst->getCondition());
1031 printValueLoad(Inst->getCaseValue(I));
1032 printSimpleInstruction("ceq");
1033 // Condition jump to successor block
1034 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1036 // Jump to default block
1037 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1041 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1042 printIndirectLoad(Inst->getOperand(0));
1043 printSimpleInstruction("call",
1044 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1045 printSimpleInstruction("refanyval","void*");
1047 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1048 printSimpleInstruction(Name.c_str());
1052 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1053 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1054 // Constant optimization.
1055 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1056 printPtrLoad(CInt->getZExtValue()*Size);
1059 printValueLoad(Inst->getOperand(0));
1060 printSimpleInstruction("mul");
1062 printSimpleInstruction("localloc");
1066 void MSILWriter::printInstruction(const Instruction* Inst) {
1067 const Value *Left = 0, *Right = 0;
1068 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1069 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1070 // Print instruction
1071 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1072 switch (Inst->getOpcode()) {
1074 case Instruction::Ret:
1075 if (Inst->getNumOperands()) {
1076 printValueLoad(Left);
1077 printSimpleInstruction("ret");
1079 printSimpleInstruction("ret");
1081 case Instruction::Br:
1082 printBranchInstruction(cast<BranchInst>(Inst));
1085 case Instruction::Add:
1086 case Instruction::FAdd:
1087 printBinaryInstruction("add",Left,Right);
1089 case Instruction::Sub:
1090 case Instruction::FSub:
1091 printBinaryInstruction("sub",Left,Right);
1093 case Instruction::Mul:
1094 case Instruction::FMul:
1095 printBinaryInstruction("mul",Left,Right);
1097 case Instruction::UDiv:
1098 printBinaryInstruction("div.un",Left,Right);
1100 case Instruction::SDiv:
1101 case Instruction::FDiv:
1102 printBinaryInstruction("div",Left,Right);
1104 case Instruction::URem:
1105 printBinaryInstruction("rem.un",Left,Right);
1107 case Instruction::SRem:
1108 case Instruction::FRem:
1109 printBinaryInstruction("rem",Left,Right);
1112 case Instruction::ICmp:
1113 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1115 case Instruction::FCmp:
1116 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1119 case Instruction::And:
1120 printBinaryInstruction("and",Left,Right);
1122 case Instruction::Or:
1123 printBinaryInstruction("or",Left,Right);
1125 case Instruction::Xor:
1126 printBinaryInstruction("xor",Left,Right);
1128 case Instruction::Shl:
1129 printValueLoad(Left);
1130 printValueLoad(Right);
1131 printSimpleInstruction("conv.i4");
1132 printSimpleInstruction("shl");
1134 case Instruction::LShr:
1135 printValueLoad(Left);
1136 printValueLoad(Right);
1137 printSimpleInstruction("conv.i4");
1138 printSimpleInstruction("shr.un");
1140 case Instruction::AShr:
1141 printValueLoad(Left);
1142 printValueLoad(Right);
1143 printSimpleInstruction("conv.i4");
1144 printSimpleInstruction("shr");
1146 case Instruction::Select:
1147 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1149 case Instruction::Load:
1150 printIndirectLoad(Inst->getOperand(0));
1152 case Instruction::Store:
1153 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1155 case Instruction::SExt:
1156 printCastInstruction(Inst->getOpcode(),Left,
1157 cast<CastInst>(Inst)->getDestTy(),
1158 cast<CastInst>(Inst)->getSrcTy());
1160 case Instruction::Trunc:
1161 case Instruction::ZExt:
1162 case Instruction::FPTrunc:
1163 case Instruction::FPExt:
1164 case Instruction::UIToFP:
1165 case Instruction::SIToFP:
1166 case Instruction::FPToUI:
1167 case Instruction::FPToSI:
1168 case Instruction::PtrToInt:
1169 case Instruction::IntToPtr:
1170 case Instruction::BitCast:
1171 printCastInstruction(Inst->getOpcode(),Left,
1172 cast<CastInst>(Inst)->getDestTy());
1174 case Instruction::GetElementPtr:
1175 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1176 gep_type_end(Inst));
1178 case Instruction::Call:
1179 printCallInstruction(cast<CallInst>(Inst));
1181 case Instruction::Invoke:
1182 printInvokeInstruction(cast<InvokeInst>(Inst));
1184 case Instruction::Unwind:
1185 printSimpleInstruction("newobj",
1186 "instance void [mscorlib]System.Exception::.ctor()");
1187 printSimpleInstruction("throw");
1189 case Instruction::Switch:
1190 printSwitchInstruction(cast<SwitchInst>(Inst));
1192 case Instruction::Alloca:
1193 printAllocaInstruction(cast<AllocaInst>(Inst));
1195 case Instruction::Malloc:
1196 llvm_unreachable("LowerAllocationsPass used");
1198 case Instruction::Free:
1199 llvm_unreachable("LowerAllocationsPass used");
1201 case Instruction::Unreachable:
1202 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1203 printSimpleInstruction("newobj",
1204 "instance void [mscorlib]System.Exception::.ctor(string)");
1205 printSimpleInstruction("throw");
1207 case Instruction::VAArg:
1208 printVAArgInstruction(cast<VAArgInst>(Inst));
1211 cerr << "Instruction = " << Inst->getName() << '\n';
1212 llvm_unreachable("Unsupported instruction");
1217 void MSILWriter::printLoop(const Loop* L) {
1218 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1219 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1220 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1221 BasicBlock* BB = blocks[I];
1222 Loop* BBLoop = LInfo->getLoopFor(BB);
1224 printBasicBlock(BB);
1225 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1228 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1232 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1233 Out << getLabelName(BB) << ":\n";
1234 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1235 const Instruction* Inst = I;
1236 // Comment llvm original instruction
1237 // Out << "\n//" << *Inst << "\n";
1238 // Do not handle PHI instruction in current block
1239 if (Inst->getOpcode()==Instruction::PHI) continue;
1240 // Print instruction
1241 printInstruction(Inst);
1243 if (Inst->getType()!=Type::VoidTy) {
1244 // Do not save value after invoke, it done in "try" block
1245 if (Inst->getOpcode()==Instruction::Invoke) continue;
1246 printValueSave(Inst);
1252 void MSILWriter::printLocalVariables(const Function& F) {
1254 const Type* Ty = NULL;
1255 std::set<const Value*> Printed;
1256 const Value* VaList = NULL;
1257 unsigned StackDepth = 8;
1258 // Find local variables
1259 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1260 if (I->getOpcode()==Instruction::Call ||
1261 I->getOpcode()==Instruction::Invoke) {
1262 // Test stack depth.
1263 if (StackDepth<I->getNumOperands())
1264 StackDepth = I->getNumOperands();
1266 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1267 if (AI && !isa<GlobalVariable>(AI)) {
1268 // Local variable allocation.
1269 Ty = PointerType::getUnqual(AI->getAllocatedType());
1270 Name = getValueName(AI);
1271 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1272 } else if (I->getType()!=Type::VoidTy) {
1273 // Operation result.
1275 Name = getValueName(&*I);
1276 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1278 // Test on 'va_list' variable
1279 bool isVaList = false;
1280 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1281 // "va_list" as "va_arg" instruction operand.
1283 VaList = VaInst->getOperand(0);
1284 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1285 // "va_list" as intrinsic function operand.
1286 switch (Inst->getIntrinsicID()) {
1287 case Intrinsic::vastart:
1288 case Intrinsic::vaend:
1289 case Intrinsic::vacopy:
1291 VaList = Inst->getOperand(1);
1297 // Print "va_list" variable.
1298 if (isVaList && Printed.insert(VaList).second) {
1299 Name = getValueName(VaList);
1300 Name.insert(Name.length()-1,"$valist");
1301 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1305 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1309 void MSILWriter::printFunctionBody(const Function& F) {
1311 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1312 if (Loop *L = LInfo->getLoopFor(I)) {
1313 if (L->getHeader()==I && L->getParentLoop()==0)
1322 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1323 const Value *left = 0, *right = 0;
1324 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1325 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1326 // Print instruction
1327 switch (CE->getOpcode()) {
1328 case Instruction::Trunc:
1329 case Instruction::ZExt:
1330 case Instruction::SExt:
1331 case Instruction::FPTrunc:
1332 case Instruction::FPExt:
1333 case Instruction::UIToFP:
1334 case Instruction::SIToFP:
1335 case Instruction::FPToUI:
1336 case Instruction::FPToSI:
1337 case Instruction::PtrToInt:
1338 case Instruction::IntToPtr:
1339 case Instruction::BitCast:
1340 printCastInstruction(CE->getOpcode(),left,CE->getType());
1342 case Instruction::GetElementPtr:
1343 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1345 case Instruction::ICmp:
1346 printICmpInstruction(CE->getPredicate(),left,right);
1348 case Instruction::FCmp:
1349 printFCmpInstruction(CE->getPredicate(),left,right);
1351 case Instruction::Select:
1352 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1354 case Instruction::Add:
1355 case Instruction::FAdd:
1356 printBinaryInstruction("add",left,right);
1358 case Instruction::Sub:
1359 case Instruction::FSub:
1360 printBinaryInstruction("sub",left,right);
1362 case Instruction::Mul:
1363 case Instruction::FMul:
1364 printBinaryInstruction("mul",left,right);
1366 case Instruction::UDiv:
1367 printBinaryInstruction("div.un",left,right);
1369 case Instruction::SDiv:
1370 case Instruction::FDiv:
1371 printBinaryInstruction("div",left,right);
1373 case Instruction::URem:
1374 printBinaryInstruction("rem.un",left,right);
1376 case Instruction::SRem:
1377 case Instruction::FRem:
1378 printBinaryInstruction("rem",left,right);
1380 case Instruction::And:
1381 printBinaryInstruction("and",left,right);
1383 case Instruction::Or:
1384 printBinaryInstruction("or",left,right);
1386 case Instruction::Xor:
1387 printBinaryInstruction("xor",left,right);
1389 case Instruction::Shl:
1390 printBinaryInstruction("shl",left,right);
1392 case Instruction::LShr:
1393 printBinaryInstruction("shr.un",left,right);
1395 case Instruction::AShr:
1396 printBinaryInstruction("shr",left,right);
1399 cerr << "Expression = " << *CE << "\n";
1400 llvm_unreachable("Invalid constant expression");
1405 void MSILWriter::printStaticInitializerList() {
1406 // List of global variables with uninitialized fields.
1407 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1408 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1410 const std::vector<StaticInitializer>& InitList = VarI->second;
1411 if (InitList.empty()) continue;
1412 // For each uninitialized field.
1413 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1414 E = InitList.end(); I!=E; ++I) {
1415 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1416 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1417 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1418 // Load variable address
1419 printValueLoad(VarI->first);
1422 printPtrLoad(I->offset);
1423 printSimpleInstruction("add");
1426 printConstantExpr(CE);
1427 // Save result at offset
1428 std::string postfix = getTypePostfix(CE->getType(),true);
1429 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1430 postfix = "stind."+postfix;
1431 printSimpleInstruction(postfix.c_str());
1433 cerr << "Constant = " << *I->constant << '\n';
1434 llvm_unreachable("Invalid static initializer");
1441 void MSILWriter::printFunction(const Function& F) {
1442 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1443 Out << "\n.method static ";
1444 Out << (F.hasLocalLinkage() ? "private " : "public ");
1445 if (F.isVarArg()) Out << "vararg ";
1446 Out << getTypeName(F.getReturnType(),isSigned) <<
1447 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1450 unsigned ArgIdx = 1;
1451 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1453 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1454 if (I!=F.arg_begin()) Out << ", ";
1455 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1457 Out << ") cil managed\n";
1460 printLocalVariables(F);
1461 printFunctionBody(F);
1466 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1468 std::set<const Type*> Printed;
1469 for (std::set<const Type*>::const_iterator
1470 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1471 const Type* Ty = *UI;
1472 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1473 Name = getTypeName(Ty, false, true);
1474 // Type with no need to declare.
1476 // Print not duplicated type
1477 if (Printed.insert(Ty).second) {
1478 Out << ".class value explicit ansi sealed '" << Name << "'";
1479 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1486 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1487 unsigned int N = Ty->getPrimitiveSizeInBits();
1488 assert(N!=0 && "Invalid type in getBitWidth()");
1497 cerr << "Bits = " << N << '\n';
1498 llvm_unreachable("Unsupported integer width");
1500 return 0; // Not reached
1504 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1505 uint64_t TySize = 0;
1506 const Type* Ty = C->getType();
1507 // Print zero initialized constant.
1508 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1509 TySize = TD->getTypeAllocSize(C->getType());
1511 Out << "int8 (0) [" << TySize << "]";
1514 // Print constant initializer
1515 switch (Ty->getTypeID()) {
1516 case Type::IntegerTyID: {
1517 TySize = TD->getTypeAllocSize(Ty);
1518 const ConstantInt* Int = cast<ConstantInt>(C);
1519 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1522 case Type::FloatTyID:
1523 case Type::DoubleTyID: {
1524 TySize = TD->getTypeAllocSize(Ty);
1525 const ConstantFP* FP = cast<ConstantFP>(C);
1526 if (Ty->getTypeID() == Type::FloatTyID)
1528 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1531 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1534 case Type::ArrayTyID:
1535 case Type::VectorTyID:
1536 case Type::StructTyID:
1537 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1538 if (I!=0) Out << ",\n";
1539 printStaticConstant(C->getOperand(I),Offset);
1542 case Type::PointerTyID:
1543 TySize = TD->getTypeAllocSize(C->getType());
1544 // Initialize with global variable address
1545 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1546 std::string name = getValueName(G);
1547 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1549 // Dynamic initialization
1550 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1551 InitListPtr->push_back(StaticInitializer(C,Offset));
1552 // Null pointer initialization
1553 if (TySize==4) Out << "int32 (0)";
1554 else if (TySize==8) Out << "int64 (0)";
1555 else llvm_unreachable("Invalid pointer size");
1559 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1560 llvm_unreachable("Invalid type in printStaticConstant()");
1567 void MSILWriter::printStaticInitializer(const Constant* C,
1568 const std::string& Name) {
1569 switch (C->getType()->getTypeID()) {
1570 case Type::IntegerTyID:
1571 case Type::FloatTyID:
1572 case Type::DoubleTyID:
1573 Out << getPrimitiveTypeName(C->getType(), false);
1575 case Type::ArrayTyID:
1576 case Type::VectorTyID:
1577 case Type::StructTyID:
1578 case Type::PointerTyID:
1579 Out << getTypeName(C->getType());
1582 cerr << "Type = " << *C << "\n";
1583 llvm_unreachable("Invalid constant type");
1585 // Print initializer
1586 std::string label = Name;
1587 label.insert(label.length()-1,"$data");
1588 Out << Name << " at " << label << '\n';
1589 Out << ".data " << label << " = {\n";
1590 uint64_t offset = 0;
1591 printStaticConstant(C,offset);
1596 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1597 const Constant* C = G->getInitializer();
1598 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1601 InitListPtr = &StaticInitList[G];
1602 printStaticInitializer(C,getValueName(G));
1606 void MSILWriter::printGlobalVariables() {
1607 if (ModulePtr->global_empty()) return;
1608 Module::global_iterator I,E;
1609 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1610 // Variable definition
1611 Out << ".field static " << (I->isDeclaration() ? "public " :
1613 if (I->isDeclaration()) {
1614 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1616 printVariableDefinition(&*I);
1621 const char* MSILWriter::getLibraryName(const Function* F) {
1622 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
1626 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1627 return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
1631 const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1633 unsigned CallingConv) {
1634 // TODO: Read *.def file with function and libraries definitions.
1635 return "MSVCRT.DLL";
1639 void MSILWriter::printExternals() {
1640 Module::const_iterator I,E;
1642 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1644 if (I->isIntrinsic()) continue;
1645 if (I->isDeclaration()) {
1646 const Function* F = I;
1647 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1649 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1650 Out << ".method static hidebysig pinvokeimpl(\""
1651 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1654 // External variables and static initialization.
1656 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1657 " native int LoadLibrary(string) preservesig {}\n"
1658 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1659 " native int GetProcAddress(native int, string) preservesig {}\n";
1661 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1664 "\tcall\tnative int LoadLibrary(string)\n"
1666 "\tcall\tnative int GetProcAddress(native int,string)\n"
1669 "\tldstr\t\"Can no import variable\"\n"
1670 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1675 ".method static private void $MSIL_Init() managed cil\n{\n";
1676 printStaticInitializerList();
1677 // Foreach global variable.
1678 for (Module::global_iterator I = ModulePtr->global_begin(),
1679 E = ModulePtr->global_end(); I!=E; ++I) {
1680 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1681 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1682 std::string Label = "not_null$_"+utostr(getUniqID());
1683 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1684 printSimpleInstruction("ldsflda",Tmp.c_str());
1685 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1686 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
1687 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1688 printIndirectSave(I->getType());
1690 printSimpleInstruction("ret");
1695 //===----------------------------------------------------------------------===//
1696 // External Interface declaration
1697 //===----------------------------------------------------------------------===//
1699 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1700 formatted_raw_ostream &o,
1701 CodeGenFileType FileType,
1702 CodeGenOpt::Level OptLevel)
1704 if (FileType != TargetMachine::AssemblyFile) return true;
1705 MSILWriter* Writer = new MSILWriter(o);
1706 PM.add(createGCLoweringPass());
1707 PM.add(createLowerAllocationsPass(true));
1708 // FIXME: Handle switch trougth native IL instruction "switch"
1709 PM.add(createLowerSwitchPass());
1710 PM.add(createCFGSimplificationPass());
1711 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1713 PM.add(createGCInfoDeleter());