bedf40385d5652d83d63ad950e1b64292fbff37f
[oota-llvm.git] / lib / Target / MSIL / MSILWriter.cpp
1 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library converts LLVM code to MSIL code.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
28
29 namespace {
30   // TargetMachine for the MSIL 
31   struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32     const TargetData DataLayout;       // Calculates type size & alignment
33
34     MSILTarget(const Target &T, const Module &M, const std::string &FS)
35       : TargetMachine(T), DataLayout(&M) {}
36
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);
42
43     // This class always works, but shouldn't be the default in most cases.
44     static unsigned getModuleMatchQuality(const Module &M) { return 1; }
45
46     virtual const TargetData *getTargetData() const { return &DataLayout; }
47   };
48 }
49
50 /// MSILTargetMachineModule - Note that this is used on hosts that
51 /// cannot link in a library unless there are references into the
52 /// library.  In particular, it seems that it is not possible to get
53 /// things to work on Win32 without this.  Though it is unused, do not
54 /// remove it.
55 extern "C" int MSILTargetMachineModule;
56 int MSILTargetMachineModule = 0;
57
58 extern Target TheMSILTarget;
59 static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
60
61 // Force static initialization.
62 extern "C" void LLVMInitializeMSILTarget() { }
63
64 bool MSILModule::runOnModule(Module &M) {
65   ModulePtr = &M;
66   TD = &getAnalysis<TargetData>();
67   bool Changed = false;
68   // Find named types.  
69   TypeSymbolTable& Table = M.getTypeSymbolTable();
70   std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
71   for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
72     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
73       Table.remove(I++);
74     else {
75       std::set<const Type *>::iterator T = Types.find(I->second);
76       if (T==Types.end())
77         Table.remove(I++);
78       else {
79         Types.erase(T);
80         ++I;
81       }
82     }
83   }
84   // Find unnamed types.
85   unsigned RenameCounter = 0;
86   for (std::set<const Type *>::const_iterator I = Types.begin(),
87        E = Types.end(); I!=E; ++I)
88     if (const StructType *STy = dyn_cast<StructType>(*I)) {
89       while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
90         ++RenameCounter;
91       Changed = true;
92     }
93   // Pointer for FunctionPass.
94   UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
95   return Changed;
96 }
97
98 char MSILModule::ID = 0;
99 char MSILWriter::ID = 0;
100
101 bool MSILWriter::runOnFunction(Function &F) {
102   if (F.isDeclaration()) return false;
103
104   // Do not codegen any 'available_externally' functions at all, they have
105   // definitions outside the translation unit.
106   if (F.hasAvailableExternallyLinkage())
107     return false;
108
109   LInfo = &getAnalysis<LoopInfo>();
110   printFunction(F);
111   return false;
112 }
113
114
115 bool MSILWriter::doInitialization(Module &M) {
116   ModulePtr = &M;
117   Mang = new Mangler(M);
118   Out << ".assembly extern mscorlib {}\n";
119   Out << ".assembly MSIL {}\n\n";
120   Out << "// External\n";
121   printExternals();
122   Out << "// Declarations\n";
123   printDeclarations(M.getTypeSymbolTable());
124   Out << "// Definitions\n";
125   printGlobalVariables();
126   Out << "// Startup code\n";
127   printModuleStartup();
128   return false;
129 }
130
131
132 bool MSILWriter::doFinalization(Module &M) {
133   delete Mang;
134   return false;
135 }
136
137
138 void MSILWriter::printModuleStartup() {
139   Out <<
140   ".method static public int32 $MSIL_Startup() {\n"
141   "\t.entrypoint\n"
142   "\t.locals (native int i)\n"
143   "\t.locals (native int argc)\n"
144   "\t.locals (native int ptr)\n"
145   "\t.locals (void* argv)\n"
146   "\t.locals (string[] args)\n"
147   "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
148   "\tdup\n"
149   "\tstloc\targs\n"
150   "\tldlen\n"
151   "\tconv.i4\n"
152   "\tdup\n"
153   "\tstloc\targc\n";
154   printPtrLoad(TD->getPointerSize());
155   Out <<
156   "\tmul\n"
157   "\tlocalloc\n"
158   "\tstloc\targv\n"
159   "\tldc.i4.0\n"
160   "\tstloc\ti\n"
161   "L_01:\n"
162   "\tldloc\ti\n"
163   "\tldloc\targc\n"
164   "\tceq\n"
165   "\tbrtrue\tL_02\n"
166   "\tldloc\targs\n"
167   "\tldloc\ti\n"
168   "\tldelem.ref\n"
169   "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
170            "StringToHGlobalAnsi(string)\n"
171   "\tstloc\tptr\n"
172   "\tldloc\targv\n"
173   "\tldloc\ti\n";
174   printPtrLoad(TD->getPointerSize());
175   Out << 
176   "\tmul\n"
177   "\tadd\n"
178   "\tldloc\tptr\n"
179   "\tstind.i\n"
180   "\tldloc\ti\n"
181   "\tldc.i4.1\n"
182   "\tadd\n"
183   "\tstloc\ti\n"
184   "\tbr\tL_01\n"
185   "L_02:\n"
186   "\tcall void $MSIL_Init()\n";
187
188   // Call user 'main' function.
189   const Function* F = ModulePtr->getFunction("main");
190   if (!F || F->isDeclaration()) {
191     Out << "\tldc.i4.0\n\tret\n}\n";
192     return;
193   }
194   bool BadSig = true;
195   std::string Args("");
196   Function::const_arg_iterator Arg1,Arg2;
197
198   switch (F->arg_size()) {
199   case 0:
200     BadSig = false;
201     break;
202   case 1:
203     Arg1 = F->arg_begin();
204     if (Arg1->getType()->isInteger()) {
205       Out << "\tldloc\targc\n";
206       Args = getTypeName(Arg1->getType());
207       BadSig = false;
208     }
209     break;
210   case 2:
211     Arg1 = Arg2 = F->arg_begin(); ++Arg2;
212     if (Arg1->getType()->isInteger() && 
213         Arg2->getType()->getTypeID() == Type::PointerTyID) {
214       Out << "\tldloc\targc\n\tldloc\targv\n";
215       Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
216       BadSig = false;
217     }
218     break;
219   default:
220     BadSig = true;
221   }
222
223   bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
224   if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
225     Out << "\tldc.i4.0\n";
226   } else {
227     Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
228       getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
229     if (RetVoid)
230       Out << "\tldc.i4.0\n";
231     else
232       Out << "\tconv.i4\n";
233   }
234   Out << "\tret\n}\n";
235 }
236
237 bool MSILWriter::isZeroValue(const Value* V) {
238   if (const Constant *C = dyn_cast<Constant>(V))
239     return C->isNullValue();
240   return false;
241 }
242
243
244 std::string MSILWriter::getValueName(const Value* V) {
245   std::string Name;
246   if (const GlobalValue *GV = cast<GlobalValue>(V))
247     Name = Mang->getMangledName(GV);
248   else {
249     unsigned &No = AnonValueNumbers[V];
250     if (No == 0) No = ++NextAnonValueNumber;
251     Name = "tmp" + utostr(No);
252   }
253   
254   // Name into the quotes allow control and space characters.
255   return "'"+Name+"'";
256 }
257
258
259 std::string MSILWriter::getLabelName(const std::string& Name) {
260   if (Name.find('.')!=std::string::npos) {
261     std::string Tmp(Name);
262     // Replace unaccepable characters in the label name.
263     for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
264       if (*I=='.') *I = '@';
265     return Tmp;
266   }
267   return Name;
268 }
269
270
271 std::string MSILWriter::getLabelName(const Value* V) {
272   std::string Name;
273   if (const GlobalValue *GV = cast<GlobalValue>(V))
274     Name = Mang->getMangledName(GV);
275   else {
276     unsigned &No = AnonValueNumbers[V];
277     if (No == 0) No = ++NextAnonValueNumber;
278     Name = "tmp" + utostr(No);
279   }
280   
281   return getLabelName(Name);
282 }
283
284
285 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
286   switch (CallingConvID) {
287   case CallingConv::C:
288   case CallingConv::Cold:
289   case CallingConv::Fast:
290     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
291   case CallingConv::X86_FastCall:
292     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
293   case CallingConv::X86_StdCall:
294     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
295   default:
296     cerr << "CallingConvID = " << CallingConvID << '\n';
297     llvm_unreachable("Unsupported calling convention");
298   }
299   return ""; // Not reached
300 }
301
302
303 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
304   std::string Tmp = "";
305   const Type* ElemTy = Ty;
306   assert(Ty->getTypeID()==TyID && "Invalid type passed");
307   // Walk trought array element types.
308   for (;;) {
309     // Multidimensional array.
310     if (ElemTy->getTypeID()==TyID) {
311       if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
312         Tmp += utostr(ATy->getNumElements());
313       else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
314         Tmp += utostr(VTy->getNumElements());
315       ElemTy = cast<SequentialType>(ElemTy)->getElementType();
316     }
317     // Base element type found.
318     if (ElemTy->getTypeID()!=TyID) break;
319     Tmp += ",";
320   }
321   return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
322 }
323
324
325 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
326   unsigned NumBits = 0;
327   switch (Ty->getTypeID()) {
328   case Type::VoidTyID:
329     return "void ";
330   case Type::IntegerTyID:
331     NumBits = getBitWidth(Ty);
332     if(NumBits==1)
333       return "bool ";
334     if (!isSigned)
335       return "unsigned int"+utostr(NumBits)+" ";
336     return "int"+utostr(NumBits)+" ";
337   case Type::FloatTyID:
338     return "float32 ";
339   case Type::DoubleTyID:
340     return "float64 "; 
341   default:
342     cerr << "Type = " << *Ty << '\n';
343     llvm_unreachable("Invalid primitive type");
344   }
345   return ""; // Not reached
346 }
347
348
349 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
350                                     bool isNested) {
351   if (Ty->isPrimitiveType() || Ty->isInteger())
352     return getPrimitiveTypeName(Ty,isSigned);
353   // FIXME: "OpaqueType" support
354   switch (Ty->getTypeID()) {
355   case Type::PointerTyID:
356     return "void* ";
357   case Type::StructTyID:
358     if (isNested)
359       return ModulePtr->getTypeName(Ty);
360     return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
361   case Type::ArrayTyID:
362     if (isNested)
363       return getArrayTypeName(Ty->getTypeID(),Ty);
364     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
365   case Type::VectorTyID:
366     if (isNested)
367       return getArrayTypeName(Ty->getTypeID(),Ty);
368     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
369   default:
370     cerr << "Type = " << *Ty << '\n';
371     llvm_unreachable("Invalid type in getTypeName()");
372   }
373   return ""; // Not reached
374 }
375
376
377 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
378   // Function argument
379   if (isa<Argument>(V))
380     return ArgumentVT;
381   // Function
382   else if (const Function* F = dyn_cast<Function>(V))
383     return F->hasLocalLinkage() ? InternalVT : GlobalVT;
384   // Variable
385   else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
386     return G->hasLocalLinkage() ? InternalVT : GlobalVT;
387   // Constant
388   else if (isa<Constant>(V))
389     return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
390   // Local variable
391   return LocalVT;
392 }
393
394
395 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
396                                        bool isSigned) {
397   unsigned NumBits = 0;
398   switch (Ty->getTypeID()) {
399   // Integer constant, expanding for stack operations.
400   case Type::IntegerTyID:
401     NumBits = getBitWidth(Ty);
402     // Expand integer value to "int32" or "int64".
403     if (Expand) return (NumBits<=32 ? "i4" : "i8");
404     if (NumBits==1) return "i1";
405     return (isSigned ? "i" : "u")+utostr(NumBits/8);
406   // Float constant.
407   case Type::FloatTyID:
408     return "r4";
409   case Type::DoubleTyID:
410     return "r8";
411   case Type::PointerTyID:
412     return "i"+utostr(TD->getTypeAllocSize(Ty));
413   default:
414     cerr << "TypeID = " << Ty->getTypeID() << '\n';
415     llvm_unreachable("Invalid type in TypeToPostfix()");
416   }
417   return ""; // Not reached
418 }
419
420
421 void MSILWriter::printConvToPtr() {
422   switch (ModulePtr->getPointerSize()) {
423   case Module::Pointer32:
424     printSimpleInstruction("conv.u4");
425     break;
426   case Module::Pointer64:
427     printSimpleInstruction("conv.u8");
428     break;
429   default:
430     llvm_unreachable("Module use not supporting pointer size");
431   }
432 }
433
434
435 void MSILWriter::printPtrLoad(uint64_t N) {
436   switch (ModulePtr->getPointerSize()) {
437   case Module::Pointer32:
438     printSimpleInstruction("ldc.i4",utostr(N).c_str());
439     // FIXME: Need overflow test?
440     if (!isUInt32(N)) {
441       cerr << "Value = " << utostr(N) << '\n';
442       llvm_unreachable("32-bit pointer overflowed");
443     }
444     break;
445   case Module::Pointer64:
446     printSimpleInstruction("ldc.i8",utostr(N).c_str());
447     break;
448   default:
449     llvm_unreachable("Module use not supporting pointer size");
450   }
451 }
452
453
454 void MSILWriter::printValuePtrLoad(const Value* V) {
455   printValueLoad(V);
456   printConvToPtr();
457 }
458
459
460 void MSILWriter::printConstLoad(const Constant* C) {
461   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
462     // Integer constant
463     Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
464     if (CInt->isMinValue(true))
465       Out << CInt->getSExtValue();
466     else
467       Out << CInt->getZExtValue();
468   } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
469     // Float constant
470     uint64_t X;
471     unsigned Size;
472     if (FP->getType()->getTypeID()==Type::FloatTyID) {
473       X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
474       Size = 4;  
475     } else {
476       X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
477       Size = 8;  
478     }
479     Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
480   } else if (isa<UndefValue>(C)) {
481     // Undefined constant value = NULL.
482     printPtrLoad(0);
483   } else {
484     cerr << "Constant = " << *C << '\n';
485     llvm_unreachable("Invalid constant value");
486   }
487   Out << '\n';
488 }
489
490
491 void MSILWriter::printValueLoad(const Value* V) {
492   MSILWriter::ValueType Location = getValueLocation(V);
493   switch (Location) {
494   // Global variable or function address.
495   case GlobalVT:
496   case InternalVT:
497     if (const Function* F = dyn_cast<Function>(V)) {
498       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
499       printSimpleInstruction("ldftn",
500         getCallSignature(F->getFunctionType(),NULL,Name).c_str());
501     } else {
502       std::string Tmp;
503       const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
504       if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
505         Tmp = "void* "+getValueName(V);
506         printSimpleInstruction("ldsfld",Tmp.c_str());
507       } else {
508         Tmp = getTypeName(ElemTy)+getValueName(V);
509         printSimpleInstruction("ldsflda",Tmp.c_str());
510       }
511     }
512     break;
513   // Function argument.
514   case ArgumentVT:
515     printSimpleInstruction("ldarg",getValueName(V).c_str());
516     break;
517   // Local function variable.
518   case LocalVT:
519     printSimpleInstruction("ldloc",getValueName(V).c_str());
520     break;
521   // Constant value.
522   case ConstVT:
523     if (isa<ConstantPointerNull>(V))
524       printPtrLoad(0);
525     else
526       printConstLoad(cast<Constant>(V));
527     break;
528   // Constant expression.
529   case ConstExprVT:
530     printConstantExpr(cast<ConstantExpr>(V));
531     break;
532   default:
533     cerr << "Value = " << *V << '\n';
534     llvm_unreachable("Invalid value location");
535   }
536 }
537
538
539 void MSILWriter::printValueSave(const Value* V) {
540   switch (getValueLocation(V)) {
541   case ArgumentVT:
542     printSimpleInstruction("starg",getValueName(V).c_str());
543     break;
544   case LocalVT:
545     printSimpleInstruction("stloc",getValueName(V).c_str());
546     break;
547   default:
548     cerr << "Value  = " << *V << '\n';
549     llvm_unreachable("Invalid value location");
550   }
551 }
552
553
554 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
555                                         const Value* Right) {
556   printValueLoad(Left);
557   printValueLoad(Right);
558   Out << '\t' << Name << '\n';
559 }
560
561
562 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
563   if(Operand) 
564     Out << '\t' << Inst << '\t' << Operand << '\n';
565   else
566     Out << '\t' << Inst << '\n';
567 }
568
569
570 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
571   for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
572        isa<PHINode>(I); ++I) {
573     const PHINode* Phi = cast<PHINode>(I);
574     const Value* Val = Phi->getIncomingValueForBlock(Src);
575     if (isa<UndefValue>(Val)) continue;
576     printValueLoad(Val);
577     printValueSave(Phi);
578   }
579 }
580
581
582 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
583                                     const BasicBlock* TrueBB,
584                                     const BasicBlock* FalseBB) {
585   if (TrueBB==FalseBB) {
586     // "TrueBB" and "FalseBB" destination equals
587     printPHICopy(CurrBB,TrueBB);
588     printSimpleInstruction("pop");
589     printSimpleInstruction("br",getLabelName(TrueBB).c_str());
590   } else if (FalseBB==NULL) {
591     // If "FalseBB" not used the jump have condition
592     printPHICopy(CurrBB,TrueBB);
593     printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
594   } else if (TrueBB==NULL) {
595     // If "TrueBB" not used the jump is unconditional
596     printPHICopy(CurrBB,FalseBB);
597     printSimpleInstruction("br",getLabelName(FalseBB).c_str());
598   } else {
599     // Copy PHI instructions for each block
600     std::string TmpLabel;
601     // Print PHI instructions for "TrueBB"
602     if (isa<PHINode>(TrueBB->begin())) {
603       TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
604       printSimpleInstruction("brtrue",TmpLabel.c_str());
605     } else {
606       printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
607     }
608     // Print PHI instructions for "FalseBB"
609     if (isa<PHINode>(FalseBB->begin())) {
610       printPHICopy(CurrBB,FalseBB);
611       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
612     } else {
613       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
614     }
615     if (isa<PHINode>(TrueBB->begin())) {
616       // Handle "TrueBB" PHI Copy
617       Out << TmpLabel << ":\n";
618       printPHICopy(CurrBB,TrueBB);
619       printSimpleInstruction("br",getLabelName(TrueBB).c_str());
620     }
621   }
622 }
623
624
625 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
626   if (Inst->isUnconditional()) {
627     printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
628   } else {
629     printValueLoad(Inst->getCondition());
630     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
631                        Inst->getSuccessor(1));
632   }
633 }
634
635
636 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
637                                         const Value* VFalse) {
638   std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
639   printValueLoad(VTrue);
640   printValueLoad(Cond);
641   printSimpleInstruction("brtrue",TmpLabel.c_str());
642   printSimpleInstruction("pop");
643   printValueLoad(VFalse);
644   Out << TmpLabel << ":\n";
645 }
646
647
648 void MSILWriter::printIndirectLoad(const Value* V) {
649   const Type* Ty = V->getType();
650   printValueLoad(V);
651   if (const PointerType* P = dyn_cast<PointerType>(Ty))
652     Ty = P->getElementType();
653   std::string Tmp = "ldind."+getTypePostfix(Ty, false);
654   printSimpleInstruction(Tmp.c_str());
655 }
656
657
658 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
659   printValueLoad(Ptr);
660   printValueLoad(Val);
661   printIndirectSave(Val->getType());
662 }
663
664
665 void MSILWriter::printIndirectSave(const Type* Ty) {
666   // Instruction need signed postfix for any type.
667   std::string postfix = getTypePostfix(Ty, false);
668   if (*postfix.begin()=='u') *postfix.begin() = 'i';
669   postfix = "stind."+postfix;
670   printSimpleInstruction(postfix.c_str());
671 }
672
673
674 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
675                                       const Type* Ty, const Type* SrcTy) {
676   std::string Tmp("");
677   printValueLoad(V);
678   switch (Op) {
679   // Signed
680   case Instruction::SExt:
681     // If sign extending int, convert first from unsigned to signed
682     // with the same bit size - because otherwise we will loose the sign.
683     if (SrcTy) {
684       Tmp = "conv."+getTypePostfix(SrcTy,false,true);
685       printSimpleInstruction(Tmp.c_str());
686     }
687     // FALLTHROUGH
688   case Instruction::SIToFP:
689   case Instruction::FPToSI:
690     Tmp = "conv."+getTypePostfix(Ty,false,true);
691     printSimpleInstruction(Tmp.c_str());
692     break;
693   // Unsigned
694   case Instruction::FPTrunc:
695   case Instruction::FPExt:
696   case Instruction::UIToFP:
697   case Instruction::Trunc:
698   case Instruction::ZExt:
699   case Instruction::FPToUI:
700   case Instruction::PtrToInt:
701   case Instruction::IntToPtr:
702     Tmp = "conv."+getTypePostfix(Ty,false);
703     printSimpleInstruction(Tmp.c_str());
704     break;
705   // Do nothing
706   case Instruction::BitCast:
707     // FIXME: meaning that ld*/st* instruction do not change data format.
708     break;
709   default:
710     cerr << "Opcode = " << Op << '\n';
711     llvm_unreachable("Invalid conversion instruction");
712   }
713 }
714
715
716 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
717                                      gep_type_iterator E) {
718   unsigned Size;
719   // Load address
720   printValuePtrLoad(V);
721   // Calculate element offset.
722   for (; I!=E; ++I){
723     Size = 0;
724     const Value* IndexValue = I.getOperand();
725     if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
726       uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
727       // Offset is the sum of all previous structure fields.
728       for (uint64_t F = 0; F<FieldIndex; ++F)
729         Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
730       printPtrLoad(Size);
731       printSimpleInstruction("add");
732       continue;
733     } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
734       Size = TD->getTypeAllocSize(SeqTy->getElementType());
735     } else {
736       Size = TD->getTypeAllocSize(*I);
737     }
738     // Add offset of current element to stack top.
739     if (!isZeroValue(IndexValue)) {
740       // Constant optimization.
741       if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
742         if (C->getValue().isNegative()) {
743           printPtrLoad(C->getValue().abs().getZExtValue()*Size);
744           printSimpleInstruction("sub");
745           continue;
746         } else
747           printPtrLoad(C->getZExtValue()*Size);
748       } else {
749         printPtrLoad(Size);
750         printValuePtrLoad(IndexValue);
751         printSimpleInstruction("mul");
752       }
753       printSimpleInstruction("add");
754     }
755   }
756 }
757
758
759 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
760                                          const Instruction* Inst,
761                                          std::string Name) {
762   std::string Tmp("");
763   if (Ty->isVarArg()) Tmp += "vararg ";
764   // Name and return type.
765   Tmp += getTypeName(Ty->getReturnType())+Name+"(";
766   // Function argument type list.
767   unsigned NumParams = Ty->getNumParams();
768   for (unsigned I = 0; I!=NumParams; ++I) {
769     if (I!=0) Tmp += ",";
770     Tmp += getTypeName(Ty->getParamType(I));
771   }
772   // CLR needs to know the exact amount of parameters received by vararg
773   // function, because caller cleans the stack.
774   if (Ty->isVarArg() && Inst) {
775     // Origin to function arguments in "CallInst" or "InvokeInst".
776     unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
777     // Print variable argument types.
778     unsigned NumOperands = Inst->getNumOperands()-Org;
779     if (NumParams<NumOperands) {
780       if (NumParams!=0) Tmp += ", ";
781       Tmp += "... , ";
782       for (unsigned J = NumParams; J!=NumOperands; ++J) {
783         if (J!=NumParams) Tmp += ", ";
784         Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
785       }
786     }
787   }
788   return Tmp+")";
789 }
790
791
792 void MSILWriter::printFunctionCall(const Value* FnVal,
793                                    const Instruction* Inst) {
794   // Get function calling convention.
795   std::string Name = "";
796   if (const CallInst* Call = dyn_cast<CallInst>(Inst))
797     Name = getConvModopt(Call->getCallingConv());
798   else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
799     Name = getConvModopt(Invoke->getCallingConv());
800   else {
801     cerr << "Instruction = " << Inst->getName() << '\n';
802     llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
803   }
804   if (const Function* F = dyn_cast<Function>(FnVal)) {
805     // Direct call.
806     Name += getValueName(F);
807     printSimpleInstruction("call",
808       getCallSignature(F->getFunctionType(),Inst,Name).c_str());
809   } else {
810     // Indirect function call.
811     const PointerType* PTy = cast<PointerType>(FnVal->getType());
812     const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
813     // Load function address.
814     printValueLoad(FnVal);
815     printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
816   }
817 }
818
819
820 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
821   std::string Name;
822   switch (Inst->getIntrinsicID()) {
823   case Intrinsic::vastart:
824     Name = getValueName(Inst->getOperand(1));
825     Name.insert(Name.length()-1,"$valist");
826     // Obtain the argument handle.
827     printSimpleInstruction("ldloca",Name.c_str());
828     printSimpleInstruction("arglist");
829     printSimpleInstruction("call",
830       "instance void [mscorlib]System.ArgIterator::.ctor"
831       "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
832     // Save as pointer type "void*"
833     printValueLoad(Inst->getOperand(1));
834     printSimpleInstruction("ldloca",Name.c_str());
835     printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
836     break;
837   case Intrinsic::vaend:
838     // Close argument list handle.
839     printIndirectLoad(Inst->getOperand(1));
840     printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
841     break;
842   case Intrinsic::vacopy:
843     // Copy "ArgIterator" valuetype.
844     printIndirectLoad(Inst->getOperand(1));
845     printIndirectLoad(Inst->getOperand(2));
846     printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
847     break;        
848   default:
849     cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
850     llvm_unreachable("Invalid intrinsic function");
851   }
852 }
853
854
855 void MSILWriter::printCallInstruction(const Instruction* Inst) {
856   if (isa<IntrinsicInst>(Inst)) {
857     // Handle intrinsic function.
858     printIntrinsicCall(cast<IntrinsicInst>(Inst));
859   } else {
860     // Load arguments to stack and call function.
861     for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
862       printValueLoad(Inst->getOperand(I));
863     printFunctionCall(Inst->getOperand(0),Inst);
864   }
865 }
866
867
868 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
869                                       const Value* Right) {
870   switch (Predicate) {
871   case ICmpInst::ICMP_EQ:
872     printBinaryInstruction("ceq",Left,Right);
873     break;
874   case ICmpInst::ICMP_NE:
875     // Emulate = not neg (Op1 eq Op2)
876     printBinaryInstruction("ceq",Left,Right);
877     printSimpleInstruction("neg");
878     printSimpleInstruction("not");
879     break;
880   case ICmpInst::ICMP_ULE:
881   case ICmpInst::ICMP_SLE:
882     // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
883     printBinaryInstruction("ceq",Left,Right);
884     if (Predicate==ICmpInst::ICMP_ULE)
885       printBinaryInstruction("clt.un",Left,Right);
886     else
887       printBinaryInstruction("clt",Left,Right);
888     printSimpleInstruction("or");
889     break;
890   case ICmpInst::ICMP_UGE:
891   case ICmpInst::ICMP_SGE:
892     // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
893     printBinaryInstruction("ceq",Left,Right);
894     if (Predicate==ICmpInst::ICMP_UGE)
895       printBinaryInstruction("cgt.un",Left,Right);
896     else
897       printBinaryInstruction("cgt",Left,Right);
898     printSimpleInstruction("or");
899     break;
900   case ICmpInst::ICMP_ULT:
901     printBinaryInstruction("clt.un",Left,Right);
902     break;
903   case ICmpInst::ICMP_SLT:
904     printBinaryInstruction("clt",Left,Right);
905     break;
906   case ICmpInst::ICMP_UGT:
907     printBinaryInstruction("cgt.un",Left,Right);
908     break;
909   case ICmpInst::ICMP_SGT:
910     printBinaryInstruction("cgt",Left,Right);
911     break;
912   default:
913     cerr << "Predicate = " << Predicate << '\n';
914     llvm_unreachable("Invalid icmp predicate");
915   }
916 }
917
918
919 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
920                                       const Value* Right) {
921   // FIXME: Correct comparison
922   std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
923   switch (Predicate) {
924   case FCmpInst::FCMP_UGT:
925     // X >  Y || llvm_fcmp_uno(X, Y)
926     printBinaryInstruction("cgt",Left,Right);
927     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
928     printSimpleInstruction("or");
929     break;
930   case FCmpInst::FCMP_OGT:
931     // X >  Y
932     printBinaryInstruction("cgt",Left,Right);
933     break;
934   case FCmpInst::FCMP_UGE:
935     // X >= Y || llvm_fcmp_uno(X, Y)
936     printBinaryInstruction("ceq",Left,Right);
937     printBinaryInstruction("cgt",Left,Right);
938     printSimpleInstruction("or");
939     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
940     printSimpleInstruction("or");
941     break;
942   case FCmpInst::FCMP_OGE:
943     // X >= Y
944     printBinaryInstruction("ceq",Left,Right);
945     printBinaryInstruction("cgt",Left,Right);
946     printSimpleInstruction("or");
947     break;
948   case FCmpInst::FCMP_ULT:
949     // X <  Y || llvm_fcmp_uno(X, Y)
950     printBinaryInstruction("clt",Left,Right);
951     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
952     printSimpleInstruction("or");
953     break;
954   case FCmpInst::FCMP_OLT:
955     // X <  Y
956     printBinaryInstruction("clt",Left,Right);
957     break;
958   case FCmpInst::FCMP_ULE:
959     // X <= Y || llvm_fcmp_uno(X, Y)
960     printBinaryInstruction("ceq",Left,Right);
961     printBinaryInstruction("clt",Left,Right);
962     printSimpleInstruction("or");
963     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
964     printSimpleInstruction("or");
965     break;
966   case FCmpInst::FCMP_OLE:
967     // X <= Y
968     printBinaryInstruction("ceq",Left,Right);
969     printBinaryInstruction("clt",Left,Right);
970     printSimpleInstruction("or");
971     break;
972   case FCmpInst::FCMP_UEQ:
973     // X == Y || llvm_fcmp_uno(X, Y)
974     printBinaryInstruction("ceq",Left,Right);
975     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
976     printSimpleInstruction("or");
977     break;
978   case FCmpInst::FCMP_OEQ:
979     // X == Y
980     printBinaryInstruction("ceq",Left,Right);
981     break;
982   case FCmpInst::FCMP_UNE:
983     // X != Y
984     printBinaryInstruction("ceq",Left,Right);
985     printSimpleInstruction("neg");
986     printSimpleInstruction("not");
987     break;
988   case FCmpInst::FCMP_ONE:
989     // X != Y && llvm_fcmp_ord(X, Y)
990     printBinaryInstruction("ceq",Left,Right);
991     printSimpleInstruction("not");
992     break;
993   case FCmpInst::FCMP_ORD:
994     // return X == X && Y == Y
995     printBinaryInstruction("ceq",Left,Left);
996     printBinaryInstruction("ceq",Right,Right);
997     printSimpleInstruction("or");
998     break;
999   case FCmpInst::FCMP_UNO:
1000     // X != X || Y != Y
1001     printBinaryInstruction("ceq",Left,Left);
1002     printSimpleInstruction("not");
1003     printBinaryInstruction("ceq",Right,Right);
1004     printSimpleInstruction("not");
1005     printSimpleInstruction("or");
1006     break;
1007   default:
1008     llvm_unreachable("Illegal FCmp predicate");
1009   }
1010 }
1011
1012
1013 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1014   std::string Label = "leave$normal_"+utostr(getUniqID());
1015   Out << ".try {\n";
1016   // Load arguments
1017   for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1018     printValueLoad(Inst->getOperand(I));
1019   // Print call instruction
1020   printFunctionCall(Inst->getOperand(0),Inst);
1021   // Save function result and leave "try" block
1022   printValueSave(Inst);
1023   printSimpleInstruction("leave",Label.c_str());
1024   Out << "}\n";
1025   Out << "catch [mscorlib]System.Exception {\n";
1026   // Redirect to unwind block
1027   printSimpleInstruction("pop");
1028   printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1029   Out << "}\n" << Label << ":\n";
1030   // Redirect to continue block
1031   printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1032 }
1033
1034
1035 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1036   // FIXME: Emulate with IL "switch" instruction
1037   // Emulate = if () else if () else if () else ...
1038   for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1039     printValueLoad(Inst->getCondition());
1040     printValueLoad(Inst->getCaseValue(I));
1041     printSimpleInstruction("ceq");
1042     // Condition jump to successor block
1043     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1044   }
1045   // Jump to default block
1046   printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1047 }
1048
1049
1050 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1051   printIndirectLoad(Inst->getOperand(0));
1052   printSimpleInstruction("call",
1053     "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1054   printSimpleInstruction("refanyval","void*");
1055   std::string Name = 
1056     "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1057   printSimpleInstruction(Name.c_str());
1058 }
1059
1060
1061 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1062   uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1063   // Constant optimization.
1064   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1065     printPtrLoad(CInt->getZExtValue()*Size);
1066   } else {
1067     printPtrLoad(Size);
1068     printValueLoad(Inst->getOperand(0));
1069     printSimpleInstruction("mul");
1070   }
1071   printSimpleInstruction("localloc");
1072 }
1073
1074
1075 void MSILWriter::printInstruction(const Instruction* Inst) {
1076   const Value *Left = 0, *Right = 0;
1077   if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1078   if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1079   // Print instruction
1080   // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1081   switch (Inst->getOpcode()) {
1082   // Terminator
1083   case Instruction::Ret:
1084     if (Inst->getNumOperands()) {
1085       printValueLoad(Left);
1086       printSimpleInstruction("ret");
1087     } else
1088       printSimpleInstruction("ret");
1089     break;
1090   case Instruction::Br:
1091     printBranchInstruction(cast<BranchInst>(Inst));
1092     break;
1093   // Binary
1094   case Instruction::Add:
1095   case Instruction::FAdd:
1096     printBinaryInstruction("add",Left,Right);
1097     break;
1098   case Instruction::Sub:
1099   case Instruction::FSub:
1100     printBinaryInstruction("sub",Left,Right);
1101     break;
1102   case Instruction::Mul:
1103   case Instruction::FMul:
1104     printBinaryInstruction("mul",Left,Right);
1105     break;
1106   case Instruction::UDiv:
1107     printBinaryInstruction("div.un",Left,Right);
1108     break;
1109   case Instruction::SDiv:
1110   case Instruction::FDiv:
1111     printBinaryInstruction("div",Left,Right);
1112     break;
1113   case Instruction::URem:
1114     printBinaryInstruction("rem.un",Left,Right);
1115     break;
1116   case Instruction::SRem:
1117   case Instruction::FRem:
1118     printBinaryInstruction("rem",Left,Right);
1119     break;
1120   // Binary Condition
1121   case Instruction::ICmp:
1122     printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1123     break;
1124   case Instruction::FCmp:
1125     printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1126     break;
1127   // Bitwise Binary
1128   case Instruction::And:
1129     printBinaryInstruction("and",Left,Right);
1130     break;
1131   case Instruction::Or:
1132     printBinaryInstruction("or",Left,Right);
1133     break;
1134   case Instruction::Xor:
1135     printBinaryInstruction("xor",Left,Right);
1136     break;
1137   case Instruction::Shl:
1138     printValueLoad(Left);
1139     printValueLoad(Right);
1140     printSimpleInstruction("conv.i4");
1141     printSimpleInstruction("shl");
1142     break;
1143   case Instruction::LShr:
1144     printValueLoad(Left);
1145     printValueLoad(Right);
1146     printSimpleInstruction("conv.i4");
1147     printSimpleInstruction("shr.un");
1148     break;
1149   case Instruction::AShr:
1150     printValueLoad(Left);
1151     printValueLoad(Right);
1152     printSimpleInstruction("conv.i4");
1153     printSimpleInstruction("shr");
1154     break;
1155   case Instruction::Select:
1156     printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1157     break;
1158   case Instruction::Load:
1159     printIndirectLoad(Inst->getOperand(0));
1160     break;
1161   case Instruction::Store:
1162     printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1163     break;
1164   case Instruction::SExt:
1165     printCastInstruction(Inst->getOpcode(),Left,
1166                          cast<CastInst>(Inst)->getDestTy(),
1167                          cast<CastInst>(Inst)->getSrcTy());
1168     break;
1169   case Instruction::Trunc:
1170   case Instruction::ZExt:
1171   case Instruction::FPTrunc:
1172   case Instruction::FPExt:
1173   case Instruction::UIToFP:
1174   case Instruction::SIToFP:
1175   case Instruction::FPToUI:
1176   case Instruction::FPToSI:
1177   case Instruction::PtrToInt:
1178   case Instruction::IntToPtr:
1179   case Instruction::BitCast:
1180     printCastInstruction(Inst->getOpcode(),Left,
1181                          cast<CastInst>(Inst)->getDestTy());
1182     break;
1183   case Instruction::GetElementPtr:
1184     printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1185                         gep_type_end(Inst));
1186     break;
1187   case Instruction::Call:
1188     printCallInstruction(cast<CallInst>(Inst));
1189     break;
1190   case Instruction::Invoke:
1191     printInvokeInstruction(cast<InvokeInst>(Inst));
1192     break;
1193   case Instruction::Unwind:
1194     printSimpleInstruction("newobj",
1195       "instance void [mscorlib]System.Exception::.ctor()");
1196     printSimpleInstruction("throw");
1197     break;
1198   case Instruction::Switch:
1199     printSwitchInstruction(cast<SwitchInst>(Inst));
1200     break;
1201   case Instruction::Alloca:
1202     printAllocaInstruction(cast<AllocaInst>(Inst));
1203     break;
1204   case Instruction::Malloc:
1205     llvm_unreachable("LowerAllocationsPass used");
1206     break;
1207   case Instruction::Free:
1208     llvm_unreachable("LowerAllocationsPass used");
1209     break;
1210   case Instruction::Unreachable:
1211     printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1212     printSimpleInstruction("newobj",
1213       "instance void [mscorlib]System.Exception::.ctor(string)");
1214     printSimpleInstruction("throw");
1215     break;
1216   case Instruction::VAArg:
1217     printVAArgInstruction(cast<VAArgInst>(Inst));
1218     break;
1219   default:
1220     cerr << "Instruction = " << Inst->getName() << '\n';
1221     llvm_unreachable("Unsupported instruction");
1222   }
1223 }
1224
1225
1226 void MSILWriter::printLoop(const Loop* L) {
1227   Out << getLabelName(L->getHeader()->getName()) << ":\n";
1228   const std::vector<BasicBlock*>& blocks = L->getBlocks();
1229   for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1230     BasicBlock* BB = blocks[I];
1231     Loop* BBLoop = LInfo->getLoopFor(BB);
1232     if (BBLoop == L)
1233       printBasicBlock(BB);
1234     else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1235       printLoop(BBLoop);
1236   }
1237   printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1238 }
1239
1240
1241 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1242   Out << getLabelName(BB) << ":\n";
1243   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1244     const Instruction* Inst = I;
1245     // Comment llvm original instruction
1246     // Out << "\n//" << *Inst << "\n";
1247     // Do not handle PHI instruction in current block
1248     if (Inst->getOpcode()==Instruction::PHI) continue;
1249     // Print instruction
1250     printInstruction(Inst);
1251     // Save result
1252     if (Inst->getType()!=Type::VoidTy) {
1253       // Do not save value after invoke, it done in "try" block
1254       if (Inst->getOpcode()==Instruction::Invoke) continue;
1255       printValueSave(Inst);
1256     }
1257   }
1258 }
1259
1260
1261 void MSILWriter::printLocalVariables(const Function& F) {
1262   std::string Name;
1263   const Type* Ty = NULL;
1264   std::set<const Value*> Printed;
1265   const Value* VaList = NULL;
1266   unsigned StackDepth = 8;
1267   // Find local variables
1268   for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1269     if (I->getOpcode()==Instruction::Call ||
1270         I->getOpcode()==Instruction::Invoke) {
1271       // Test stack depth.
1272       if (StackDepth<I->getNumOperands())
1273         StackDepth = I->getNumOperands();
1274     }
1275     const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1276     if (AI && !isa<GlobalVariable>(AI)) {
1277       // Local variable allocation.
1278       Ty = PointerType::getUnqual(AI->getAllocatedType());
1279       Name = getValueName(AI);
1280       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1281     } else if (I->getType()!=Type::VoidTy) {
1282       // Operation result.
1283       Ty = I->getType();
1284       Name = getValueName(&*I);
1285       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1286     }
1287     // Test on 'va_list' variable    
1288     bool isVaList = false;     
1289     if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1290       // "va_list" as "va_arg" instruction operand.
1291       isVaList = true;
1292       VaList = VaInst->getOperand(0);
1293     } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1294       // "va_list" as intrinsic function operand. 
1295       switch (Inst->getIntrinsicID()) {
1296       case Intrinsic::vastart:
1297       case Intrinsic::vaend:
1298       case Intrinsic::vacopy:
1299         isVaList = true;
1300         VaList = Inst->getOperand(1);
1301         break;
1302       default:
1303         isVaList = false;
1304       }
1305     }
1306     // Print "va_list" variable.
1307     if (isVaList && Printed.insert(VaList).second) {
1308       Name = getValueName(VaList);
1309       Name.insert(Name.length()-1,"$valist");
1310       Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1311           << Name << ")\n";
1312     }
1313   }
1314   printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1315 }
1316
1317
1318 void MSILWriter::printFunctionBody(const Function& F) {
1319   // Print body
1320   for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1321     if (Loop *L = LInfo->getLoopFor(I)) {
1322       if (L->getHeader()==I && L->getParentLoop()==0)
1323         printLoop(L);
1324     } else {
1325       printBasicBlock(I);
1326     }
1327   }
1328 }
1329
1330
1331 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1332   const Value *left = 0, *right = 0;
1333   if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1334   if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1335   // Print instruction
1336   switch (CE->getOpcode()) {
1337   case Instruction::Trunc:
1338   case Instruction::ZExt:
1339   case Instruction::SExt:
1340   case Instruction::FPTrunc:
1341   case Instruction::FPExt:
1342   case Instruction::UIToFP:
1343   case Instruction::SIToFP:
1344   case Instruction::FPToUI:
1345   case Instruction::FPToSI:
1346   case Instruction::PtrToInt:
1347   case Instruction::IntToPtr:
1348   case Instruction::BitCast:
1349     printCastInstruction(CE->getOpcode(),left,CE->getType());
1350     break;
1351   case Instruction::GetElementPtr:
1352     printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1353     break;
1354   case Instruction::ICmp:
1355     printICmpInstruction(CE->getPredicate(),left,right);
1356     break;
1357   case Instruction::FCmp:
1358     printFCmpInstruction(CE->getPredicate(),left,right);
1359     break;
1360   case Instruction::Select:
1361     printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1362     break;
1363   case Instruction::Add:
1364   case Instruction::FAdd:
1365     printBinaryInstruction("add",left,right);
1366     break;
1367   case Instruction::Sub:
1368   case Instruction::FSub:
1369     printBinaryInstruction("sub",left,right);
1370     break;
1371   case Instruction::Mul:
1372   case Instruction::FMul:
1373     printBinaryInstruction("mul",left,right);
1374     break;
1375   case Instruction::UDiv:
1376     printBinaryInstruction("div.un",left,right);
1377     break;
1378   case Instruction::SDiv:
1379   case Instruction::FDiv:
1380     printBinaryInstruction("div",left,right);
1381     break;
1382   case Instruction::URem:
1383     printBinaryInstruction("rem.un",left,right);
1384     break;
1385   case Instruction::SRem:
1386   case Instruction::FRem:
1387     printBinaryInstruction("rem",left,right);
1388     break;
1389   case Instruction::And:
1390     printBinaryInstruction("and",left,right);
1391     break;
1392   case Instruction::Or:
1393     printBinaryInstruction("or",left,right);
1394     break;
1395   case Instruction::Xor:
1396     printBinaryInstruction("xor",left,right);
1397     break;
1398   case Instruction::Shl:
1399     printBinaryInstruction("shl",left,right);
1400     break;
1401   case Instruction::LShr:
1402     printBinaryInstruction("shr.un",left,right);
1403     break;
1404   case Instruction::AShr:
1405     printBinaryInstruction("shr",left,right);
1406     break;
1407   default:
1408     cerr << "Expression = " << *CE << "\n";
1409     llvm_unreachable("Invalid constant expression");
1410   }
1411 }
1412
1413
1414 void MSILWriter::printStaticInitializerList() {
1415   // List of global variables with uninitialized fields.
1416   for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1417        VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1418        ++VarI) {
1419     const std::vector<StaticInitializer>& InitList = VarI->second;
1420     if (InitList.empty()) continue;
1421     // For each uninitialized field.
1422     for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1423          E = InitList.end(); I!=E; ++I) {
1424       if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1425         // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1426         //  utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1427         // Load variable address
1428         printValueLoad(VarI->first);
1429         // Add offset
1430         if (I->offset!=0) {
1431           printPtrLoad(I->offset);
1432           printSimpleInstruction("add");
1433         }
1434         // Load value
1435         printConstantExpr(CE);
1436         // Save result at offset
1437         std::string postfix = getTypePostfix(CE->getType(),true);
1438         if (*postfix.begin()=='u') *postfix.begin() = 'i';
1439         postfix = "stind."+postfix;
1440         printSimpleInstruction(postfix.c_str());
1441       } else {
1442         cerr << "Constant = " << *I->constant << '\n';
1443         llvm_unreachable("Invalid static initializer");
1444       }
1445     }
1446   }
1447 }
1448
1449
1450 void MSILWriter::printFunction(const Function& F) {
1451   bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1452   Out << "\n.method static ";
1453   Out << (F.hasLocalLinkage() ? "private " : "public ");
1454   if (F.isVarArg()) Out << "vararg ";
1455   Out << getTypeName(F.getReturnType(),isSigned) << 
1456     getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1457   // Arguments
1458   Out << "\t(";
1459   unsigned ArgIdx = 1;
1460   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1461        ++I, ++ArgIdx) {
1462     isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1463     if (I!=F.arg_begin()) Out << ", ";
1464     Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1465   }
1466   Out << ") cil managed\n";
1467   // Body
1468   Out << "{\n";
1469   printLocalVariables(F);
1470   printFunctionBody(F);
1471   Out << "}\n";
1472 }
1473
1474
1475 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1476   std::string Name;
1477   std::set<const Type*> Printed;
1478   for (std::set<const Type*>::const_iterator
1479        UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1480     const Type* Ty = *UI;
1481     if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1482       Name = getTypeName(Ty, false, true);
1483     // Type with no need to declare.
1484     else continue;
1485     // Print not duplicated type
1486     if (Printed.insert(Ty).second) {
1487       Out << ".class value explicit ansi sealed '" << Name << "'";
1488       Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1489       Out << " }\n\n";
1490     }
1491   }
1492 }
1493
1494
1495 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1496   unsigned int N = Ty->getPrimitiveSizeInBits();
1497   assert(N!=0 && "Invalid type in getBitWidth()");
1498   switch (N) {
1499   case 1:
1500   case 8:
1501   case 16:
1502   case 32:
1503   case 64:
1504     return N;
1505   default:
1506     cerr << "Bits = " << N << '\n';
1507     llvm_unreachable("Unsupported integer width");
1508   }
1509   return 0; // Not reached
1510 }
1511
1512
1513 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1514   uint64_t TySize = 0;
1515   const Type* Ty = C->getType();
1516   // Print zero initialized constant.
1517   if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1518     TySize = TD->getTypeAllocSize(C->getType());
1519     Offset += TySize;
1520     Out << "int8 (0) [" << TySize << "]";
1521     return;
1522   }
1523   // Print constant initializer
1524   switch (Ty->getTypeID()) {
1525   case Type::IntegerTyID: {
1526     TySize = TD->getTypeAllocSize(Ty);
1527     const ConstantInt* Int = cast<ConstantInt>(C);
1528     Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1529     break;
1530   }
1531   case Type::FloatTyID:
1532   case Type::DoubleTyID: {
1533     TySize = TD->getTypeAllocSize(Ty);
1534     const ConstantFP* FP = cast<ConstantFP>(C);
1535     if (Ty->getTypeID() == Type::FloatTyID)
1536       Out << "int32 (" << 
1537         (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1538     else
1539       Out << "int64 (" << 
1540         FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1541     break;
1542   }
1543   case Type::ArrayTyID:
1544   case Type::VectorTyID:
1545   case Type::StructTyID:
1546     for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1547       if (I!=0) Out << ",\n";
1548       printStaticConstant(C->getOperand(I),Offset);
1549     }
1550     break;
1551   case Type::PointerTyID:
1552     TySize = TD->getTypeAllocSize(C->getType());
1553     // Initialize with global variable address
1554     if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1555       std::string name = getValueName(G);
1556       Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1557     } else {
1558       // Dynamic initialization
1559       if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1560         InitListPtr->push_back(StaticInitializer(C,Offset));
1561       // Null pointer initialization
1562       if (TySize==4) Out << "int32 (0)";
1563       else if (TySize==8) Out << "int64 (0)";
1564       else llvm_unreachable("Invalid pointer size");
1565     }
1566     break;
1567   default:
1568     cerr << "TypeID = " << Ty->getTypeID() << '\n';
1569     llvm_unreachable("Invalid type in printStaticConstant()");
1570   }
1571   // Increase offset.
1572   Offset += TySize;
1573 }
1574
1575
1576 void MSILWriter::printStaticInitializer(const Constant* C,
1577                                         const std::string& Name) {
1578   switch (C->getType()->getTypeID()) {
1579   case Type::IntegerTyID:
1580   case Type::FloatTyID:
1581   case Type::DoubleTyID: 
1582     Out << getPrimitiveTypeName(C->getType(), false);
1583     break;
1584   case Type::ArrayTyID:
1585   case Type::VectorTyID:
1586   case Type::StructTyID:
1587   case Type::PointerTyID:
1588     Out << getTypeName(C->getType());
1589     break;
1590   default:
1591     cerr << "Type = " << *C << "\n";
1592     llvm_unreachable("Invalid constant type");
1593   }
1594   // Print initializer
1595   std::string label = Name;
1596   label.insert(label.length()-1,"$data");
1597   Out << Name << " at " << label << '\n';
1598   Out << ".data " << label << " = {\n";
1599   uint64_t offset = 0;
1600   printStaticConstant(C,offset);
1601   Out << "\n}\n\n";
1602 }
1603
1604
1605 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1606   const Constant* C = G->getInitializer();
1607   if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1608     InitListPtr = 0;
1609   else
1610     InitListPtr = &StaticInitList[G];
1611   printStaticInitializer(C,getValueName(G));
1612 }
1613
1614
1615 void MSILWriter::printGlobalVariables() {
1616   if (ModulePtr->global_empty()) return;
1617   Module::global_iterator I,E;
1618   for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1619     // Variable definition
1620     Out << ".field static " << (I->isDeclaration() ? "public " :
1621                                                      "private ");
1622     if (I->isDeclaration()) {
1623       Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1624     } else
1625       printVariableDefinition(&*I);
1626   }
1627 }
1628
1629
1630 const char* MSILWriter::getLibraryName(const Function* F) {
1631   return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1632 }
1633
1634
1635 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1636   return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
1637 }
1638
1639
1640 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1641                                            unsigned CallingConv) {
1642   // TODO: Read *.def file with function and libraries definitions.
1643   return "MSVCRT.DLL";  
1644 }
1645
1646
1647 void MSILWriter::printExternals() {
1648   Module::const_iterator I,E;
1649   // Functions.
1650   for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1651     // Skip intrisics
1652     if (I->isIntrinsic()) continue;
1653     if (I->isDeclaration()) {
1654       const Function* F = I; 
1655       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1656       std::string Sig = 
1657         getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1658       Out << ".method static hidebysig pinvokeimpl(\""
1659           << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1660     }
1661   }
1662   // External variables and static initialization.
1663   Out <<
1664   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1665   "  native int LoadLibrary(string) preservesig {}\n"
1666   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1667   "  native int GetProcAddress(native int, string) preservesig {}\n";
1668   Out <<
1669   ".method private static void* $MSIL_Import(string lib,string sym)\n"
1670   " managed cil\n{\n"
1671   "\tldarg\tlib\n"
1672   "\tcall\tnative int LoadLibrary(string)\n"
1673   "\tldarg\tsym\n"
1674   "\tcall\tnative int GetProcAddress(native int,string)\n"
1675   "\tdup\n"
1676   "\tbrtrue\tL_01\n"
1677   "\tldstr\t\"Can no import variable\"\n"
1678   "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1679   "\tthrow\n"
1680   "L_01:\n"
1681   "\tret\n"
1682   "}\n\n"
1683   ".method static private void $MSIL_Init() managed cil\n{\n";
1684   printStaticInitializerList();
1685   // Foreach global variable.
1686   for (Module::global_iterator I = ModulePtr->global_begin(),
1687        E = ModulePtr->global_end(); I!=E; ++I) {
1688     if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1689     // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1690     std::string Label = "not_null$_"+utostr(getUniqID());
1691     std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1692     printSimpleInstruction("ldsflda",Tmp.c_str());
1693     Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1694     Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
1695     printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1696     printIndirectSave(I->getType());
1697   }
1698   printSimpleInstruction("ret");
1699   Out << "}\n\n";
1700 }
1701
1702
1703 //===----------------------------------------------------------------------===//
1704 //                      External Interface declaration
1705 //===----------------------------------------------------------------------===//
1706
1707 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1708                                           formatted_raw_ostream &o,
1709                                           CodeGenFileType FileType,
1710                                           CodeGenOpt::Level OptLevel)
1711 {
1712   if (FileType != TargetMachine::AssemblyFile) return true;
1713   MSILWriter* Writer = new MSILWriter(o);
1714   PM.add(createGCLoweringPass());
1715   PM.add(createLowerAllocationsPass(true));
1716   // FIXME: Handle switch trougth native IL instruction "switch"
1717   PM.add(createLowerSwitchPass());
1718   PM.add(createCFGSimplificationPass());
1719   PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1720   PM.add(Writer);
1721   PM.add(createGCInfoDeleter());
1722   return false;
1723 }