Switch this API to StringRef.
[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 static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
51
52 // Force static initialization.
53 extern "C" void LLVMInitializeMSILTarget() { }
54
55 bool MSILModule::runOnModule(Module &M) {
56   ModulePtr = &M;
57   TD = &getAnalysis<TargetData>();
58   bool Changed = false;
59   // Find named types.  
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))
64       Table.remove(I++);
65     else {
66       std::set<const Type *>::iterator T = Types.find(I->second);
67       if (T==Types.end())
68         Table.remove(I++);
69       else {
70         Types.erase(T);
71         ++I;
72       }
73     }
74   }
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))
81         ++RenameCounter;
82       Changed = true;
83     }
84   // Pointer for FunctionPass.
85   UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
86   return Changed;
87 }
88
89 char MSILModule::ID = 0;
90 char MSILWriter::ID = 0;
91
92 bool MSILWriter::runOnFunction(Function &F) {
93   if (F.isDeclaration()) return false;
94
95   // Do not codegen any 'available_externally' functions at all, they have
96   // definitions outside the translation unit.
97   if (F.hasAvailableExternallyLinkage())
98     return false;
99
100   LInfo = &getAnalysis<LoopInfo>();
101   printFunction(F);
102   return false;
103 }
104
105
106 bool MSILWriter::doInitialization(Module &M) {
107   ModulePtr = &M;
108   Mang = new Mangler(M);
109   Out << ".assembly extern mscorlib {}\n";
110   Out << ".assembly MSIL {}\n\n";
111   Out << "// External\n";
112   printExternals();
113   Out << "// Declarations\n";
114   printDeclarations(M.getTypeSymbolTable());
115   Out << "// Definitions\n";
116   printGlobalVariables();
117   Out << "// Startup code\n";
118   printModuleStartup();
119   return false;
120 }
121
122
123 bool MSILWriter::doFinalization(Module &M) {
124   delete Mang;
125   return false;
126 }
127
128
129 void MSILWriter::printModuleStartup() {
130   Out <<
131   ".method static public int32 $MSIL_Startup() {\n"
132   "\t.entrypoint\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"
139   "\tdup\n"
140   "\tstloc\targs\n"
141   "\tldlen\n"
142   "\tconv.i4\n"
143   "\tdup\n"
144   "\tstloc\targc\n";
145   printPtrLoad(TD->getPointerSize());
146   Out <<
147   "\tmul\n"
148   "\tlocalloc\n"
149   "\tstloc\targv\n"
150   "\tldc.i4.0\n"
151   "\tstloc\ti\n"
152   "L_01:\n"
153   "\tldloc\ti\n"
154   "\tldloc\targc\n"
155   "\tceq\n"
156   "\tbrtrue\tL_02\n"
157   "\tldloc\targs\n"
158   "\tldloc\ti\n"
159   "\tldelem.ref\n"
160   "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
161            "StringToHGlobalAnsi(string)\n"
162   "\tstloc\tptr\n"
163   "\tldloc\targv\n"
164   "\tldloc\ti\n";
165   printPtrLoad(TD->getPointerSize());
166   Out << 
167   "\tmul\n"
168   "\tadd\n"
169   "\tldloc\tptr\n"
170   "\tstind.i\n"
171   "\tldloc\ti\n"
172   "\tldc.i4.1\n"
173   "\tadd\n"
174   "\tstloc\ti\n"
175   "\tbr\tL_01\n"
176   "L_02:\n"
177   "\tcall void $MSIL_Init()\n";
178
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";
183     return;
184   }
185   bool BadSig = true;
186   std::string Args("");
187   Function::const_arg_iterator Arg1,Arg2;
188
189   switch (F->arg_size()) {
190   case 0:
191     BadSig = false;
192     break;
193   case 1:
194     Arg1 = F->arg_begin();
195     if (Arg1->getType()->isInteger()) {
196       Out << "\tldloc\targc\n";
197       Args = getTypeName(Arg1->getType());
198       BadSig = false;
199     }
200     break;
201   case 2:
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());
207       BadSig = false;
208     }
209     break;
210   default:
211     BadSig = true;
212   }
213
214   bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
215   if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
216     Out << "\tldc.i4.0\n";
217   } else {
218     Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
219       getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
220     if (RetVoid)
221       Out << "\tldc.i4.0\n";
222     else
223       Out << "\tconv.i4\n";
224   }
225   Out << "\tret\n}\n";
226 }
227
228 bool MSILWriter::isZeroValue(const Value* V) {
229   if (const Constant *C = dyn_cast<Constant>(V))
230     return C->isNullValue();
231   return false;
232 }
233
234
235 std::string MSILWriter::getValueName(const Value* V) {
236   std::string Name;
237   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
238     Name = Mang->getMangledName(GV);
239   else {
240     unsigned &No = AnonValueNumbers[V];
241     if (No == 0) No = ++NextAnonValueNumber;
242     Name = "tmp" + utostr(No);
243   }
244   
245   // Name into the quotes allow control and space characters.
246   return "'"+Name+"'";
247 }
248
249
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 = '@';
256     return Tmp;
257   }
258   return Name;
259 }
260
261
262 std::string MSILWriter::getLabelName(const Value* V) {
263   std::string Name;
264   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
265     Name = Mang->getMangledName(GV);
266   else {
267     unsigned &No = AnonValueNumbers[V];
268     if (No == 0) No = ++NextAnonValueNumber;
269     Name = "tmp" + utostr(No);
270   }
271   
272   return getLabelName(Name);
273 }
274
275
276 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
277   switch (CallingConvID) {
278   case CallingConv::C:
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) ";
286   default:
287     cerr << "CallingConvID = " << CallingConvID << '\n';
288     llvm_unreachable("Unsupported calling convention");
289   }
290   return ""; // Not reached
291 }
292
293
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.
299   for (;;) {
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();
307     }
308     // Base element type found.
309     if (ElemTy->getTypeID()!=TyID) break;
310     Tmp += ",";
311   }
312   return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
313 }
314
315
316 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
317   unsigned NumBits = 0;
318   switch (Ty->getTypeID()) {
319   case Type::VoidTyID:
320     return "void ";
321   case Type::IntegerTyID:
322     NumBits = getBitWidth(Ty);
323     if(NumBits==1)
324       return "bool ";
325     if (!isSigned)
326       return "unsigned int"+utostr(NumBits)+" ";
327     return "int"+utostr(NumBits)+" ";
328   case Type::FloatTyID:
329     return "float32 ";
330   case Type::DoubleTyID:
331     return "float64 "; 
332   default:
333     cerr << "Type = " << *Ty << '\n';
334     llvm_unreachable("Invalid primitive type");
335   }
336   return ""; // Not reached
337 }
338
339
340 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
341                                     bool isNested) {
342   if (Ty->isPrimitiveType() || Ty->isInteger())
343     return getPrimitiveTypeName(Ty,isSigned);
344   // FIXME: "OpaqueType" support
345   switch (Ty->getTypeID()) {
346   case Type::PointerTyID:
347     return "void* ";
348   case Type::StructTyID:
349     if (isNested)
350       return ModulePtr->getTypeName(Ty);
351     return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
352   case Type::ArrayTyID:
353     if (isNested)
354       return getArrayTypeName(Ty->getTypeID(),Ty);
355     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
356   case Type::VectorTyID:
357     if (isNested)
358       return getArrayTypeName(Ty->getTypeID(),Ty);
359     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
360   default:
361     cerr << "Type = " << *Ty << '\n';
362     llvm_unreachable("Invalid type in getTypeName()");
363   }
364   return ""; // Not reached
365 }
366
367
368 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
369   // Function argument
370   if (isa<Argument>(V))
371     return ArgumentVT;
372   // Function
373   else if (const Function* F = dyn_cast<Function>(V))
374     return F->hasLocalLinkage() ? InternalVT : GlobalVT;
375   // Variable
376   else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
377     return G->hasLocalLinkage() ? InternalVT : GlobalVT;
378   // Constant
379   else if (isa<Constant>(V))
380     return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
381   // Local variable
382   return LocalVT;
383 }
384
385
386 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
387                                        bool isSigned) {
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);
397   // Float constant.
398   case Type::FloatTyID:
399     return "r4";
400   case Type::DoubleTyID:
401     return "r8";
402   case Type::PointerTyID:
403     return "i"+utostr(TD->getTypeAllocSize(Ty));
404   default:
405     cerr << "TypeID = " << Ty->getTypeID() << '\n';
406     llvm_unreachable("Invalid type in TypeToPostfix()");
407   }
408   return ""; // Not reached
409 }
410
411
412 void MSILWriter::printConvToPtr() {
413   switch (ModulePtr->getPointerSize()) {
414   case Module::Pointer32:
415     printSimpleInstruction("conv.u4");
416     break;
417   case Module::Pointer64:
418     printSimpleInstruction("conv.u8");
419     break;
420   default:
421     llvm_unreachable("Module use not supporting pointer size");
422   }
423 }
424
425
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?
431     if (!isUInt32(N)) {
432       cerr << "Value = " << utostr(N) << '\n';
433       llvm_unreachable("32-bit pointer overflowed");
434     }
435     break;
436   case Module::Pointer64:
437     printSimpleInstruction("ldc.i8",utostr(N).c_str());
438     break;
439   default:
440     llvm_unreachable("Module use not supporting pointer size");
441   }
442 }
443
444
445 void MSILWriter::printValuePtrLoad(const Value* V) {
446   printValueLoad(V);
447   printConvToPtr();
448 }
449
450
451 void MSILWriter::printConstLoad(const Constant* C) {
452   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
453     // Integer constant
454     Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
455     if (CInt->isMinValue(true))
456       Out << CInt->getSExtValue();
457     else
458       Out << CInt->getZExtValue();
459   } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
460     // Float constant
461     uint64_t X;
462     unsigned Size;
463     if (FP->getType()->getTypeID()==Type::FloatTyID) {
464       X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
465       Size = 4;  
466     } else {
467       X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
468       Size = 8;  
469     }
470     Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
471   } else if (isa<UndefValue>(C)) {
472     // Undefined constant value = NULL.
473     printPtrLoad(0);
474   } else {
475     cerr << "Constant = " << *C << '\n';
476     llvm_unreachable("Invalid constant value");
477   }
478   Out << '\n';
479 }
480
481
482 void MSILWriter::printValueLoad(const Value* V) {
483   MSILWriter::ValueType Location = getValueLocation(V);
484   switch (Location) {
485   // Global variable or function address.
486   case GlobalVT:
487   case InternalVT:
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());
492     } else {
493       std::string Tmp;
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());
498       } else {
499         Tmp = getTypeName(ElemTy)+getValueName(V);
500         printSimpleInstruction("ldsflda",Tmp.c_str());
501       }
502     }
503     break;
504   // Function argument.
505   case ArgumentVT:
506     printSimpleInstruction("ldarg",getValueName(V).c_str());
507     break;
508   // Local function variable.
509   case LocalVT:
510     printSimpleInstruction("ldloc",getValueName(V).c_str());
511     break;
512   // Constant value.
513   case ConstVT:
514     if (isa<ConstantPointerNull>(V))
515       printPtrLoad(0);
516     else
517       printConstLoad(cast<Constant>(V));
518     break;
519   // Constant expression.
520   case ConstExprVT:
521     printConstantExpr(cast<ConstantExpr>(V));
522     break;
523   default:
524     cerr << "Value = " << *V << '\n';
525     llvm_unreachable("Invalid value location");
526   }
527 }
528
529
530 void MSILWriter::printValueSave(const Value* V) {
531   switch (getValueLocation(V)) {
532   case ArgumentVT:
533     printSimpleInstruction("starg",getValueName(V).c_str());
534     break;
535   case LocalVT:
536     printSimpleInstruction("stloc",getValueName(V).c_str());
537     break;
538   default:
539     cerr << "Value  = " << *V << '\n';
540     llvm_unreachable("Invalid value location");
541   }
542 }
543
544
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';
550 }
551
552
553 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
554   if(Operand) 
555     Out << '\t' << Inst << '\t' << Operand << '\n';
556   else
557     Out << '\t' << Inst << '\n';
558 }
559
560
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;
567     printValueLoad(Val);
568     printValueSave(Phi);
569   }
570 }
571
572
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());
589   } else {
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());
596     } else {
597       printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
598     }
599     // Print PHI instructions for "FalseBB"
600     if (isa<PHINode>(FalseBB->begin())) {
601       printPHICopy(CurrBB,FalseBB);
602       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
603     } else {
604       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
605     }
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());
611     }
612   }
613 }
614
615
616 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
617   if (Inst->isUnconditional()) {
618     printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
619   } else {
620     printValueLoad(Inst->getCondition());
621     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
622                        Inst->getSuccessor(1));
623   }
624 }
625
626
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";
636 }
637
638
639 void MSILWriter::printIndirectLoad(const Value* V) {
640   const Type* Ty = V->getType();
641   printValueLoad(V);
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());
646 }
647
648
649 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
650   printValueLoad(Ptr);
651   printValueLoad(Val);
652   printIndirectSave(Val->getType());
653 }
654
655
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());
662 }
663
664
665 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
666                                       const Type* Ty, const Type* SrcTy) {
667   std::string Tmp("");
668   printValueLoad(V);
669   switch (Op) {
670   // Signed
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.
674     if (SrcTy) {
675       Tmp = "conv."+getTypePostfix(SrcTy,false,true);
676       printSimpleInstruction(Tmp.c_str());
677     }
678     // FALLTHROUGH
679   case Instruction::SIToFP:
680   case Instruction::FPToSI:
681     Tmp = "conv."+getTypePostfix(Ty,false,true);
682     printSimpleInstruction(Tmp.c_str());
683     break;
684   // Unsigned
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());
695     break;
696   // Do nothing
697   case Instruction::BitCast:
698     // FIXME: meaning that ld*/st* instruction do not change data format.
699     break;
700   default:
701     cerr << "Opcode = " << Op << '\n';
702     llvm_unreachable("Invalid conversion instruction");
703   }
704 }
705
706
707 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
708                                      gep_type_iterator E) {
709   unsigned Size;
710   // Load address
711   printValuePtrLoad(V);
712   // Calculate element offset.
713   for (; I!=E; ++I){
714     Size = 0;
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));
721       printPtrLoad(Size);
722       printSimpleInstruction("add");
723       continue;
724     } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
725       Size = TD->getTypeAllocSize(SeqTy->getElementType());
726     } else {
727       Size = TD->getTypeAllocSize(*I);
728     }
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");
736           continue;
737         } else
738           printPtrLoad(C->getZExtValue()*Size);
739       } else {
740         printPtrLoad(Size);
741         printValuePtrLoad(IndexValue);
742         printSimpleInstruction("mul");
743       }
744       printSimpleInstruction("add");
745     }
746   }
747 }
748
749
750 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
751                                          const Instruction* Inst,
752                                          std::string Name) {
753   std::string Tmp("");
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));
762   }
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 += ", ";
772       Tmp += "... , ";
773       for (unsigned J = NumParams; J!=NumOperands; ++J) {
774         if (J!=NumParams) Tmp += ", ";
775         Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
776       }
777     }
778   }
779   return Tmp+")";
780 }
781
782
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());
791   else {
792     cerr << "Instruction = " << Inst->getName() << '\n';
793     llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
794   }
795   if (const Function* F = dyn_cast<Function>(FnVal)) {
796     // Direct call.
797     Name += getValueName(F);
798     printSimpleInstruction("call",
799       getCallSignature(F->getFunctionType(),Inst,Name).c_str());
800   } else {
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());
807   }
808 }
809
810
811 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
812   std::string Name;
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)));
827     break;
828   case Intrinsic::vaend:
829     // Close argument list handle.
830     printIndirectLoad(Inst->getOperand(1));
831     printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
832     break;
833   case Intrinsic::vacopy:
834     // Copy "ArgIterator" valuetype.
835     printIndirectLoad(Inst->getOperand(1));
836     printIndirectLoad(Inst->getOperand(2));
837     printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
838     break;        
839   default:
840     cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
841     llvm_unreachable("Invalid intrinsic function");
842   }
843 }
844
845
846 void MSILWriter::printCallInstruction(const Instruction* Inst) {
847   if (isa<IntrinsicInst>(Inst)) {
848     // Handle intrinsic function.
849     printIntrinsicCall(cast<IntrinsicInst>(Inst));
850   } else {
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);
855   }
856 }
857
858
859 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
860                                       const Value* Right) {
861   switch (Predicate) {
862   case ICmpInst::ICMP_EQ:
863     printBinaryInstruction("ceq",Left,Right);
864     break;
865   case ICmpInst::ICMP_NE:
866     // Emulate = not neg (Op1 eq Op2)
867     printBinaryInstruction("ceq",Left,Right);
868     printSimpleInstruction("neg");
869     printSimpleInstruction("not");
870     break;
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);
877     else
878       printBinaryInstruction("clt",Left,Right);
879     printSimpleInstruction("or");
880     break;
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);
887     else
888       printBinaryInstruction("cgt",Left,Right);
889     printSimpleInstruction("or");
890     break;
891   case ICmpInst::ICMP_ULT:
892     printBinaryInstruction("clt.un",Left,Right);
893     break;
894   case ICmpInst::ICMP_SLT:
895     printBinaryInstruction("clt",Left,Right);
896     break;
897   case ICmpInst::ICMP_UGT:
898     printBinaryInstruction("cgt.un",Left,Right);
899     break;
900   case ICmpInst::ICMP_SGT:
901     printBinaryInstruction("cgt",Left,Right);
902     break;
903   default:
904     cerr << "Predicate = " << Predicate << '\n';
905     llvm_unreachable("Invalid icmp predicate");
906   }
907 }
908
909
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)";
914   switch (Predicate) {
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");
920     break;
921   case FCmpInst::FCMP_OGT:
922     // X >  Y
923     printBinaryInstruction("cgt",Left,Right);
924     break;
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");
932     break;
933   case FCmpInst::FCMP_OGE:
934     // X >= Y
935     printBinaryInstruction("ceq",Left,Right);
936     printBinaryInstruction("cgt",Left,Right);
937     printSimpleInstruction("or");
938     break;
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");
944     break;
945   case FCmpInst::FCMP_OLT:
946     // X <  Y
947     printBinaryInstruction("clt",Left,Right);
948     break;
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");
956     break;
957   case FCmpInst::FCMP_OLE:
958     // X <= Y
959     printBinaryInstruction("ceq",Left,Right);
960     printBinaryInstruction("clt",Left,Right);
961     printSimpleInstruction("or");
962     break;
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");
968     break;
969   case FCmpInst::FCMP_OEQ:
970     // X == Y
971     printBinaryInstruction("ceq",Left,Right);
972     break;
973   case FCmpInst::FCMP_UNE:
974     // X != Y
975     printBinaryInstruction("ceq",Left,Right);
976     printSimpleInstruction("neg");
977     printSimpleInstruction("not");
978     break;
979   case FCmpInst::FCMP_ONE:
980     // X != Y && llvm_fcmp_ord(X, Y)
981     printBinaryInstruction("ceq",Left,Right);
982     printSimpleInstruction("not");
983     break;
984   case FCmpInst::FCMP_ORD:
985     // return X == X && Y == Y
986     printBinaryInstruction("ceq",Left,Left);
987     printBinaryInstruction("ceq",Right,Right);
988     printSimpleInstruction("or");
989     break;
990   case FCmpInst::FCMP_UNO:
991     // X != X || Y != Y
992     printBinaryInstruction("ceq",Left,Left);
993     printSimpleInstruction("not");
994     printBinaryInstruction("ceq",Right,Right);
995     printSimpleInstruction("not");
996     printSimpleInstruction("or");
997     break;
998   default:
999     llvm_unreachable("Illegal FCmp predicate");
1000   }
1001 }
1002
1003
1004 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1005   std::string Label = "leave$normal_"+utostr(getUniqID());
1006   Out << ".try {\n";
1007   // Load arguments
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());
1015   Out << "}\n";
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());
1023 }
1024
1025
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);
1035   }
1036   // Jump to default block
1037   printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1038 }
1039
1040
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*");
1046   std::string Name = 
1047     "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1048   printSimpleInstruction(Name.c_str());
1049 }
1050
1051
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);
1057   } else {
1058     printPtrLoad(Size);
1059     printValueLoad(Inst->getOperand(0));
1060     printSimpleInstruction("mul");
1061   }
1062   printSimpleInstruction("localloc");
1063 }
1064
1065
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()) {
1073   // Terminator
1074   case Instruction::Ret:
1075     if (Inst->getNumOperands()) {
1076       printValueLoad(Left);
1077       printSimpleInstruction("ret");
1078     } else
1079       printSimpleInstruction("ret");
1080     break;
1081   case Instruction::Br:
1082     printBranchInstruction(cast<BranchInst>(Inst));
1083     break;
1084   // Binary
1085   case Instruction::Add:
1086   case Instruction::FAdd:
1087     printBinaryInstruction("add",Left,Right);
1088     break;
1089   case Instruction::Sub:
1090   case Instruction::FSub:
1091     printBinaryInstruction("sub",Left,Right);
1092     break;
1093   case Instruction::Mul:
1094   case Instruction::FMul:
1095     printBinaryInstruction("mul",Left,Right);
1096     break;
1097   case Instruction::UDiv:
1098     printBinaryInstruction("div.un",Left,Right);
1099     break;
1100   case Instruction::SDiv:
1101   case Instruction::FDiv:
1102     printBinaryInstruction("div",Left,Right);
1103     break;
1104   case Instruction::URem:
1105     printBinaryInstruction("rem.un",Left,Right);
1106     break;
1107   case Instruction::SRem:
1108   case Instruction::FRem:
1109     printBinaryInstruction("rem",Left,Right);
1110     break;
1111   // Binary Condition
1112   case Instruction::ICmp:
1113     printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1114     break;
1115   case Instruction::FCmp:
1116     printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1117     break;
1118   // Bitwise Binary
1119   case Instruction::And:
1120     printBinaryInstruction("and",Left,Right);
1121     break;
1122   case Instruction::Or:
1123     printBinaryInstruction("or",Left,Right);
1124     break;
1125   case Instruction::Xor:
1126     printBinaryInstruction("xor",Left,Right);
1127     break;
1128   case Instruction::Shl:
1129     printValueLoad(Left);
1130     printValueLoad(Right);
1131     printSimpleInstruction("conv.i4");
1132     printSimpleInstruction("shl");
1133     break;
1134   case Instruction::LShr:
1135     printValueLoad(Left);
1136     printValueLoad(Right);
1137     printSimpleInstruction("conv.i4");
1138     printSimpleInstruction("shr.un");
1139     break;
1140   case Instruction::AShr:
1141     printValueLoad(Left);
1142     printValueLoad(Right);
1143     printSimpleInstruction("conv.i4");
1144     printSimpleInstruction("shr");
1145     break;
1146   case Instruction::Select:
1147     printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1148     break;
1149   case Instruction::Load:
1150     printIndirectLoad(Inst->getOperand(0));
1151     break;
1152   case Instruction::Store:
1153     printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1154     break;
1155   case Instruction::SExt:
1156     printCastInstruction(Inst->getOpcode(),Left,
1157                          cast<CastInst>(Inst)->getDestTy(),
1158                          cast<CastInst>(Inst)->getSrcTy());
1159     break;
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());
1173     break;
1174   case Instruction::GetElementPtr:
1175     printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1176                         gep_type_end(Inst));
1177     break;
1178   case Instruction::Call:
1179     printCallInstruction(cast<CallInst>(Inst));
1180     break;
1181   case Instruction::Invoke:
1182     printInvokeInstruction(cast<InvokeInst>(Inst));
1183     break;
1184   case Instruction::Unwind:
1185     printSimpleInstruction("newobj",
1186       "instance void [mscorlib]System.Exception::.ctor()");
1187     printSimpleInstruction("throw");
1188     break;
1189   case Instruction::Switch:
1190     printSwitchInstruction(cast<SwitchInst>(Inst));
1191     break;
1192   case Instruction::Alloca:
1193     printAllocaInstruction(cast<AllocaInst>(Inst));
1194     break;
1195   case Instruction::Malloc:
1196     llvm_unreachable("LowerAllocationsPass used");
1197     break;
1198   case Instruction::Free:
1199     llvm_unreachable("LowerAllocationsPass used");
1200     break;
1201   case Instruction::Unreachable:
1202     printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1203     printSimpleInstruction("newobj",
1204       "instance void [mscorlib]System.Exception::.ctor(string)");
1205     printSimpleInstruction("throw");
1206     break;
1207   case Instruction::VAArg:
1208     printVAArgInstruction(cast<VAArgInst>(Inst));
1209     break;
1210   default:
1211     cerr << "Instruction = " << Inst->getName() << '\n';
1212     llvm_unreachable("Unsupported instruction");
1213   }
1214 }
1215
1216
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);
1223     if (BBLoop == L)
1224       printBasicBlock(BB);
1225     else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1226       printLoop(BBLoop);
1227   }
1228   printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1229 }
1230
1231
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);
1242     // Save result
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);
1247     }
1248   }
1249 }
1250
1251
1252 void MSILWriter::printLocalVariables(const Function& F) {
1253   std::string Name;
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();
1265     }
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.
1274       Ty = I->getType();
1275       Name = getValueName(&*I);
1276       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1277     }
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.
1282       isVaList = true;
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:
1290         isVaList = true;
1291         VaList = Inst->getOperand(1);
1292         break;
1293       default:
1294         isVaList = false;
1295       }
1296     }
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 "
1302           << Name << ")\n";
1303     }
1304   }
1305   printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1306 }
1307
1308
1309 void MSILWriter::printFunctionBody(const Function& F) {
1310   // Print body
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)
1314         printLoop(L);
1315     } else {
1316       printBasicBlock(I);
1317     }
1318   }
1319 }
1320
1321
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());
1341     break;
1342   case Instruction::GetElementPtr:
1343     printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1344     break;
1345   case Instruction::ICmp:
1346     printICmpInstruction(CE->getPredicate(),left,right);
1347     break;
1348   case Instruction::FCmp:
1349     printFCmpInstruction(CE->getPredicate(),left,right);
1350     break;
1351   case Instruction::Select:
1352     printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1353     break;
1354   case Instruction::Add:
1355   case Instruction::FAdd:
1356     printBinaryInstruction("add",left,right);
1357     break;
1358   case Instruction::Sub:
1359   case Instruction::FSub:
1360     printBinaryInstruction("sub",left,right);
1361     break;
1362   case Instruction::Mul:
1363   case Instruction::FMul:
1364     printBinaryInstruction("mul",left,right);
1365     break;
1366   case Instruction::UDiv:
1367     printBinaryInstruction("div.un",left,right);
1368     break;
1369   case Instruction::SDiv:
1370   case Instruction::FDiv:
1371     printBinaryInstruction("div",left,right);
1372     break;
1373   case Instruction::URem:
1374     printBinaryInstruction("rem.un",left,right);
1375     break;
1376   case Instruction::SRem:
1377   case Instruction::FRem:
1378     printBinaryInstruction("rem",left,right);
1379     break;
1380   case Instruction::And:
1381     printBinaryInstruction("and",left,right);
1382     break;
1383   case Instruction::Or:
1384     printBinaryInstruction("or",left,right);
1385     break;
1386   case Instruction::Xor:
1387     printBinaryInstruction("xor",left,right);
1388     break;
1389   case Instruction::Shl:
1390     printBinaryInstruction("shl",left,right);
1391     break;
1392   case Instruction::LShr:
1393     printBinaryInstruction("shr.un",left,right);
1394     break;
1395   case Instruction::AShr:
1396     printBinaryInstruction("shr",left,right);
1397     break;
1398   default:
1399     cerr << "Expression = " << *CE << "\n";
1400     llvm_unreachable("Invalid constant expression");
1401   }
1402 }
1403
1404
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;
1409        ++VarI) {
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);
1420         // Add offset
1421         if (I->offset!=0) {
1422           printPtrLoad(I->offset);
1423           printSimpleInstruction("add");
1424         }
1425         // Load value
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());
1432       } else {
1433         cerr << "Constant = " << *I->constant << '\n';
1434         llvm_unreachable("Invalid static initializer");
1435       }
1436     }
1437   }
1438 }
1439
1440
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';
1448   // Arguments
1449   Out << "\t(";
1450   unsigned ArgIdx = 1;
1451   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1452        ++I, ++ArgIdx) {
1453     isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1454     if (I!=F.arg_begin()) Out << ", ";
1455     Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1456   }
1457   Out << ") cil managed\n";
1458   // Body
1459   Out << "{\n";
1460   printLocalVariables(F);
1461   printFunctionBody(F);
1462   Out << "}\n";
1463 }
1464
1465
1466 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1467   std::string Name;
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.
1475     else continue;
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);
1480       Out << " }\n\n";
1481     }
1482   }
1483 }
1484
1485
1486 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1487   unsigned int N = Ty->getPrimitiveSizeInBits();
1488   assert(N!=0 && "Invalid type in getBitWidth()");
1489   switch (N) {
1490   case 1:
1491   case 8:
1492   case 16:
1493   case 32:
1494   case 64:
1495     return N;
1496   default:
1497     cerr << "Bits = " << N << '\n';
1498     llvm_unreachable("Unsupported integer width");
1499   }
1500   return 0; // Not reached
1501 }
1502
1503
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());
1510     Offset += TySize;
1511     Out << "int8 (0) [" << TySize << "]";
1512     return;
1513   }
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() << ")";
1520     break;
1521   }
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)
1527       Out << "int32 (" << 
1528         (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1529     else
1530       Out << "int64 (" << 
1531         FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1532     break;
1533   }
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);
1540     }
1541     break;
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") << ")";
1548     } else {
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");
1556     }
1557     break;
1558   default:
1559     cerr << "TypeID = " << Ty->getTypeID() << '\n';
1560     llvm_unreachable("Invalid type in printStaticConstant()");
1561   }
1562   // Increase offset.
1563   Offset += TySize;
1564 }
1565
1566
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);
1574     break;
1575   case Type::ArrayTyID:
1576   case Type::VectorTyID:
1577   case Type::StructTyID:
1578   case Type::PointerTyID:
1579     Out << getTypeName(C->getType());
1580     break;
1581   default:
1582     cerr << "Type = " << *C << "\n";
1583     llvm_unreachable("Invalid constant type");
1584   }
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);
1592   Out << "\n}\n\n";
1593 }
1594
1595
1596 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1597   const Constant* C = G->getInitializer();
1598   if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1599     InitListPtr = 0;
1600   else
1601     InitListPtr = &StaticInitList[G];
1602   printStaticInitializer(C,getValueName(G));
1603 }
1604
1605
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 " :
1612                                                      "private ");
1613     if (I->isDeclaration()) {
1614       Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1615     } else
1616       printVariableDefinition(&*I);
1617   }
1618 }
1619
1620
1621 const char* MSILWriter::getLibraryName(const Function* F) {
1622   return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
1623 }
1624
1625
1626 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1627   return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
1628 }
1629
1630
1631 const char* MSILWriter::getLibraryForSymbol(const StringRef &Name, 
1632                                             bool isFunction,
1633                                             unsigned CallingConv) {
1634   // TODO: Read *.def file with function and libraries definitions.
1635   return "MSVCRT.DLL";  
1636 }
1637
1638
1639 void MSILWriter::printExternals() {
1640   Module::const_iterator I,E;
1641   // Functions.
1642   for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1643     // Skip intrisics
1644     if (I->isIntrinsic()) continue;
1645     if (I->isDeclaration()) {
1646       const Function* F = I; 
1647       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1648       std::string Sig = 
1649         getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1650       Out << ".method static hidebysig pinvokeimpl(\""
1651           << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1652     }
1653   }
1654   // External variables and static initialization.
1655   Out <<
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";
1660   Out <<
1661   ".method private static void* $MSIL_Import(string lib,string sym)\n"
1662   " managed cil\n{\n"
1663   "\tldarg\tlib\n"
1664   "\tcall\tnative int LoadLibrary(string)\n"
1665   "\tldarg\tsym\n"
1666   "\tcall\tnative int GetProcAddress(native int,string)\n"
1667   "\tdup\n"
1668   "\tbrtrue\tL_01\n"
1669   "\tldstr\t\"Can no import variable\"\n"
1670   "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1671   "\tthrow\n"
1672   "L_01:\n"
1673   "\tret\n"
1674   "}\n\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());
1689   }
1690   printSimpleInstruction("ret");
1691   Out << "}\n\n";
1692 }
1693
1694
1695 //===----------------------------------------------------------------------===//
1696 //                      External Interface declaration
1697 //===----------------------------------------------------------------------===//
1698
1699 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1700                                           formatted_raw_ostream &o,
1701                                           CodeGenFileType FileType,
1702                                           CodeGenOpt::Level OptLevel)
1703 {
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));
1712   PM.add(Writer);
1713   PM.add(createGCInfoDeleter());
1714   return false;
1715 }