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