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