blob: ad0364907fd858af5d4ecd8a0cb7e9906593bbb9 [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000023#include "llvm/Support/InstVisitor.h"
Anton Korobeynikovf13090c2007-05-06 20:13:33 +000024#include "llvm/Support/MathExtras.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000025#include "llvm/Transforms/Scalar.h"
26#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000027#include "llvm/CodeGen/Passes.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000028
29namespace {
30 // TargetMachine for the MSIL
31 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32 const TargetData DataLayout; // Calculates type size & alignment
33
Daniel Dunbar51b198a2009-07-15 20:24:03 +000034 MSILTarget(const Target &T, const Module &M, const std::string &FS)
35 : TargetMachine(T), DataLayout(&M) {}
Anton Korobeynikov099883f2007-03-21 21:38:25 +000036
37 virtual bool WantsWholeFile() const { return true; }
David Greene71847812009-07-14 20:18:05 +000038 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000040 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +000041 CodeGenOpt::Level OptLevel);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000042
43 // This class always works, but shouldn't be the default in most cases.
44 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
45
46 virtual const TargetData *getTargetData() const { return &DataLayout; }
47 };
48}
49
Daniel Dunbar51b198a2009-07-15 20:24:03 +000050static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000051
Bob Wilsona96751f2009-06-23 23:59:40 +000052// Force static initialization.
53extern "C" void LLVMInitializeMSILTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000054
Anton Korobeynikov099883f2007-03-21 21:38:25 +000055bool MSILModule::runOnModule(Module &M) {
56 ModulePtr = &M;
57 TD = &getAnalysis<TargetData>();
58 bool Changed = false;
59 // Find named types.
60 TypeSymbolTable& Table = M.getTypeSymbolTable();
61 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
62 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
63 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
64 Table.remove(I++);
65 else {
66 std::set<const Type *>::iterator T = Types.find(I->second);
67 if (T==Types.end())
68 Table.remove(I++);
69 else {
70 Types.erase(T);
71 ++I;
72 }
73 }
74 }
75 // Find unnamed types.
76 unsigned RenameCounter = 0;
77 for (std::set<const Type *>::const_iterator I = Types.begin(),
78 E = Types.end(); I!=E; ++I)
79 if (const StructType *STy = dyn_cast<StructType>(*I)) {
80 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
81 ++RenameCounter;
82 Changed = true;
83 }
84 // Pointer for FunctionPass.
85 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
86 return Changed;
87}
88
Devang Patel19974732007-05-03 01:11:54 +000089char MSILModule::ID = 0;
90char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000091
92bool MSILWriter::runOnFunction(Function &F) {
93 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000094
95 // Do not codegen any 'available_externally' functions at all, they have
96 // definitions outside the translation unit.
97 if (F.hasAvailableExternallyLinkage())
98 return false;
99
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000100 LInfo = &getAnalysis<LoopInfo>();
101 printFunction(F);
102 return false;
103}
104
105
106bool MSILWriter::doInitialization(Module &M) {
107 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000108 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000109 Out << ".assembly extern mscorlib {}\n";
110 Out << ".assembly MSIL {}\n\n";
111 Out << "// External\n";
112 printExternals();
113 Out << "// Declarations\n";
114 printDeclarations(M.getTypeSymbolTable());
115 Out << "// Definitions\n";
116 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000117 Out << "// Startup code\n";
118 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000119 return false;
120}
121
122
123bool MSILWriter::doFinalization(Module &M) {
124 delete Mang;
125 return false;
126}
127
128
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000129void MSILWriter::printModuleStartup() {
130 Out <<
131 ".method static public int32 $MSIL_Startup() {\n"
132 "\t.entrypoint\n"
133 "\t.locals (native int i)\n"
134 "\t.locals (native int argc)\n"
135 "\t.locals (native int ptr)\n"
136 "\t.locals (void* argv)\n"
137 "\t.locals (string[] args)\n"
138 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
139 "\tdup\n"
140 "\tstloc\targs\n"
141 "\tldlen\n"
142 "\tconv.i4\n"
143 "\tdup\n"
144 "\tstloc\targc\n";
145 printPtrLoad(TD->getPointerSize());
146 Out <<
147 "\tmul\n"
148 "\tlocalloc\n"
149 "\tstloc\targv\n"
150 "\tldc.i4.0\n"
151 "\tstloc\ti\n"
152 "L_01:\n"
153 "\tldloc\ti\n"
154 "\tldloc\targc\n"
155 "\tceq\n"
156 "\tbrtrue\tL_02\n"
157 "\tldloc\targs\n"
158 "\tldloc\ti\n"
159 "\tldelem.ref\n"
160 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
161 "StringToHGlobalAnsi(string)\n"
162 "\tstloc\tptr\n"
163 "\tldloc\targv\n"
164 "\tldloc\ti\n";
165 printPtrLoad(TD->getPointerSize());
166 Out <<
167 "\tmul\n"
168 "\tadd\n"
169 "\tldloc\tptr\n"
170 "\tstind.i\n"
171 "\tldloc\ti\n"
172 "\tldc.i4.1\n"
173 "\tadd\n"
174 "\tstloc\ti\n"
175 "\tbr\tL_01\n"
176 "L_02:\n"
177 "\tcall void $MSIL_Init()\n";
178
179 // Call user 'main' function.
180 const Function* F = ModulePtr->getFunction("main");
181 if (!F || F->isDeclaration()) {
182 Out << "\tldc.i4.0\n\tret\n}\n";
183 return;
184 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000185 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000186 std::string Args("");
187 Function::const_arg_iterator Arg1,Arg2;
188
189 switch (F->arg_size()) {
190 case 0:
191 BadSig = false;
192 break;
193 case 1:
194 Arg1 = F->arg_begin();
195 if (Arg1->getType()->isInteger()) {
196 Out << "\tldloc\targc\n";
197 Args = getTypeName(Arg1->getType());
198 BadSig = false;
199 }
200 break;
201 case 2:
202 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
203 if (Arg1->getType()->isInteger() &&
204 Arg2->getType()->getTypeID() == Type::PointerTyID) {
205 Out << "\tldloc\targc\n\tldloc\targv\n";
206 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
207 BadSig = false;
208 }
209 break;
210 default:
211 BadSig = true;
212 }
213
214 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000215 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000216 Out << "\tldc.i4.0\n";
217 } else {
218 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
219 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
220 if (RetVoid)
221 Out << "\tldc.i4.0\n";
222 else
223 Out << "\tconv.i4\n";
224 }
225 Out << "\tret\n}\n";
226}
227
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000228bool MSILWriter::isZeroValue(const Value* V) {
229 if (const Constant *C = dyn_cast<Constant>(V))
230 return C->isNullValue();
231 return false;
232}
233
234
235std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000236 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000237 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000238 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000239 else {
240 unsigned &No = AnonValueNumbers[V];
241 if (No == 0) No = ++NextAnonValueNumber;
242 Name = "tmp" + utostr(No);
243 }
244
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000245 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000246 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000247}
248
249
250std::string MSILWriter::getLabelName(const std::string& Name) {
251 if (Name.find('.')!=std::string::npos) {
252 std::string Tmp(Name);
253 // Replace unaccepable characters in the label name.
254 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
255 if (*I=='.') *I = '@';
256 return Tmp;
257 }
258 return Name;
259}
260
261
262std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000263 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000264 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000265 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000266 else {
267 unsigned &No = AnonValueNumbers[V];
268 if (No == 0) No = ++NextAnonValueNumber;
269 Name = "tmp" + utostr(No);
270 }
271
272 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000273}
274
275
276std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
277 switch (CallingConvID) {
278 case CallingConv::C:
279 case CallingConv::Cold:
280 case CallingConv::Fast:
281 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
282 case CallingConv::X86_FastCall:
283 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
284 case CallingConv::X86_StdCall:
285 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
286 default:
287 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000288 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000289 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000290 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000291}
292
293
294std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
295 std::string Tmp = "";
296 const Type* ElemTy = Ty;
297 assert(Ty->getTypeID()==TyID && "Invalid type passed");
298 // Walk trought array element types.
299 for (;;) {
300 // Multidimensional array.
301 if (ElemTy->getTypeID()==TyID) {
302 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
303 Tmp += utostr(ATy->getNumElements());
304 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
305 Tmp += utostr(VTy->getNumElements());
306 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
307 }
308 // Base element type found.
309 if (ElemTy->getTypeID()!=TyID) break;
310 Tmp += ",";
311 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000312 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000313}
314
315
316std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
317 unsigned NumBits = 0;
318 switch (Ty->getTypeID()) {
319 case Type::VoidTyID:
320 return "void ";
321 case Type::IntegerTyID:
322 NumBits = getBitWidth(Ty);
323 if(NumBits==1)
324 return "bool ";
325 if (!isSigned)
326 return "unsigned int"+utostr(NumBits)+" ";
327 return "int"+utostr(NumBits)+" ";
328 case Type::FloatTyID:
329 return "float32 ";
330 case Type::DoubleTyID:
331 return "float64 ";
332 default:
333 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000334 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000335 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000336 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000337}
338
339
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000340std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
341 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000342 if (Ty->isPrimitiveType() || Ty->isInteger())
343 return getPrimitiveTypeName(Ty,isSigned);
344 // FIXME: "OpaqueType" support
345 switch (Ty->getTypeID()) {
346 case Type::PointerTyID:
347 return "void* ";
348 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000349 if (isNested)
350 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000351 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
352 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000353 if (isNested)
354 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000355 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
356 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000357 if (isNested)
358 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000359 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
360 default:
361 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000362 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000363 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000364 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000365}
366
367
368MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
369 // Function argument
370 if (isa<Argument>(V))
371 return ArgumentVT;
372 // Function
373 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000374 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000375 // Variable
376 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000377 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000378 // Constant
379 else if (isa<Constant>(V))
380 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
381 // Local variable
382 return LocalVT;
383}
384
385
386std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
387 bool isSigned) {
388 unsigned NumBits = 0;
389 switch (Ty->getTypeID()) {
390 // Integer constant, expanding for stack operations.
391 case Type::IntegerTyID:
392 NumBits = getBitWidth(Ty);
393 // Expand integer value to "int32" or "int64".
394 if (Expand) return (NumBits<=32 ? "i4" : "i8");
395 if (NumBits==1) return "i1";
396 return (isSigned ? "i" : "u")+utostr(NumBits/8);
397 // Float constant.
398 case Type::FloatTyID:
399 return "r4";
400 case Type::DoubleTyID:
401 return "r8";
402 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000403 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000404 default:
405 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000406 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000407 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000408 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000409}
410
411
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000412void MSILWriter::printConvToPtr() {
413 switch (ModulePtr->getPointerSize()) {
414 case Module::Pointer32:
415 printSimpleInstruction("conv.u4");
416 break;
417 case Module::Pointer64:
418 printSimpleInstruction("conv.u8");
419 break;
420 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000421 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000422 }
423}
424
425
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000426void MSILWriter::printPtrLoad(uint64_t N) {
427 switch (ModulePtr->getPointerSize()) {
428 case Module::Pointer32:
429 printSimpleInstruction("ldc.i4",utostr(N).c_str());
430 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000431 if (!isUInt32(N)) {
432 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000433 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000434 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000435 break;
436 case Module::Pointer64:
437 printSimpleInstruction("ldc.i8",utostr(N).c_str());
438 break;
439 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000440 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000441 }
442}
443
444
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000445void MSILWriter::printValuePtrLoad(const Value* V) {
446 printValueLoad(V);
447 printConvToPtr();
448}
449
450
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000451void MSILWriter::printConstLoad(const Constant* C) {
452 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
453 // Integer constant
454 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
455 if (CInt->isMinValue(true))
456 Out << CInt->getSExtValue();
457 else
458 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000459 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000460 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000461 uint64_t X;
462 unsigned Size;
463 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000464 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000465 Size = 4;
466 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000467 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000468 Size = 8;
469 }
470 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
471 } else if (isa<UndefValue>(C)) {
472 // Undefined constant value = NULL.
473 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000474 } else {
475 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000476 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000477 }
478 Out << '\n';
479}
480
481
482void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000483 MSILWriter::ValueType Location = getValueLocation(V);
484 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000485 // Global variable or function address.
486 case GlobalVT:
487 case InternalVT:
488 if (const Function* F = dyn_cast<Function>(V)) {
489 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
490 printSimpleInstruction("ldftn",
491 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
492 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000493 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000494 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000495 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
496 Tmp = "void* "+getValueName(V);
497 printSimpleInstruction("ldsfld",Tmp.c_str());
498 } else {
499 Tmp = getTypeName(ElemTy)+getValueName(V);
500 printSimpleInstruction("ldsflda",Tmp.c_str());
501 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000502 }
503 break;
504 // Function argument.
505 case ArgumentVT:
506 printSimpleInstruction("ldarg",getValueName(V).c_str());
507 break;
508 // Local function variable.
509 case LocalVT:
510 printSimpleInstruction("ldloc",getValueName(V).c_str());
511 break;
512 // Constant value.
513 case ConstVT:
514 if (isa<ConstantPointerNull>(V))
515 printPtrLoad(0);
516 else
517 printConstLoad(cast<Constant>(V));
518 break;
519 // Constant expression.
520 case ConstExprVT:
521 printConstantExpr(cast<ConstantExpr>(V));
522 break;
523 default:
524 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000525 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000526 }
527}
528
529
530void MSILWriter::printValueSave(const Value* V) {
531 switch (getValueLocation(V)) {
532 case ArgumentVT:
533 printSimpleInstruction("starg",getValueName(V).c_str());
534 break;
535 case LocalVT:
536 printSimpleInstruction("stloc",getValueName(V).c_str());
537 break;
538 default:
539 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000540 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000541 }
542}
543
544
545void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
546 const Value* Right) {
547 printValueLoad(Left);
548 printValueLoad(Right);
549 Out << '\t' << Name << '\n';
550}
551
552
553void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
554 if(Operand)
555 Out << '\t' << Inst << '\t' << Operand << '\n';
556 else
557 Out << '\t' << Inst << '\n';
558}
559
560
561void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
562 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
563 isa<PHINode>(I); ++I) {
564 const PHINode* Phi = cast<PHINode>(I);
565 const Value* Val = Phi->getIncomingValueForBlock(Src);
566 if (isa<UndefValue>(Val)) continue;
567 printValueLoad(Val);
568 printValueSave(Phi);
569 }
570}
571
572
573void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
574 const BasicBlock* TrueBB,
575 const BasicBlock* FalseBB) {
576 if (TrueBB==FalseBB) {
577 // "TrueBB" and "FalseBB" destination equals
578 printPHICopy(CurrBB,TrueBB);
579 printSimpleInstruction("pop");
580 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
581 } else if (FalseBB==NULL) {
582 // If "FalseBB" not used the jump have condition
583 printPHICopy(CurrBB,TrueBB);
584 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
585 } else if (TrueBB==NULL) {
586 // If "TrueBB" not used the jump is unconditional
587 printPHICopy(CurrBB,FalseBB);
588 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
589 } else {
590 // Copy PHI instructions for each block
591 std::string TmpLabel;
592 // Print PHI instructions for "TrueBB"
593 if (isa<PHINode>(TrueBB->begin())) {
594 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
595 printSimpleInstruction("brtrue",TmpLabel.c_str());
596 } else {
597 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
598 }
599 // Print PHI instructions for "FalseBB"
600 if (isa<PHINode>(FalseBB->begin())) {
601 printPHICopy(CurrBB,FalseBB);
602 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
603 } else {
604 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
605 }
606 if (isa<PHINode>(TrueBB->begin())) {
607 // Handle "TrueBB" PHI Copy
608 Out << TmpLabel << ":\n";
609 printPHICopy(CurrBB,TrueBB);
610 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
611 }
612 }
613}
614
615
616void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
617 if (Inst->isUnconditional()) {
618 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
619 } else {
620 printValueLoad(Inst->getCondition());
621 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
622 Inst->getSuccessor(1));
623 }
624}
625
626
627void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
628 const Value* VFalse) {
629 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
630 printValueLoad(VTrue);
631 printValueLoad(Cond);
632 printSimpleInstruction("brtrue",TmpLabel.c_str());
633 printSimpleInstruction("pop");
634 printValueLoad(VFalse);
635 Out << TmpLabel << ":\n";
636}
637
638
639void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000640 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000641 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000642 if (const PointerType* P = dyn_cast<PointerType>(Ty))
643 Ty = P->getElementType();
644 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000645 printSimpleInstruction(Tmp.c_str());
646}
647
648
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000649void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000650 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000651 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000652 printIndirectSave(Val->getType());
653}
654
655
656void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000657 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000658 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000659 if (*postfix.begin()=='u') *postfix.begin() = 'i';
660 postfix = "stind."+postfix;
661 printSimpleInstruction(postfix.c_str());
662}
663
664
665void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000666 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000667 std::string Tmp("");
668 printValueLoad(V);
669 switch (Op) {
670 // Signed
671 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000672 // If sign extending int, convert first from unsigned to signed
673 // with the same bit size - because otherwise we will loose the sign.
674 if (SrcTy) {
675 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
676 printSimpleInstruction(Tmp.c_str());
677 }
Bill Wendling5f544502009-07-14 18:30:04 +0000678 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000679 case Instruction::SIToFP:
680 case Instruction::FPToSI:
681 Tmp = "conv."+getTypePostfix(Ty,false,true);
682 printSimpleInstruction(Tmp.c_str());
683 break;
684 // Unsigned
685 case Instruction::FPTrunc:
686 case Instruction::FPExt:
687 case Instruction::UIToFP:
688 case Instruction::Trunc:
689 case Instruction::ZExt:
690 case Instruction::FPToUI:
691 case Instruction::PtrToInt:
692 case Instruction::IntToPtr:
693 Tmp = "conv."+getTypePostfix(Ty,false);
694 printSimpleInstruction(Tmp.c_str());
695 break;
696 // Do nothing
697 case Instruction::BitCast:
698 // FIXME: meaning that ld*/st* instruction do not change data format.
699 break;
700 default:
701 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000702 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000703 }
704}
705
706
707void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
708 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000709 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000710 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000711 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000712 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000713 for (; I!=E; ++I){
714 Size = 0;
715 const Value* IndexValue = I.getOperand();
716 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
717 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
718 // Offset is the sum of all previous structure fields.
719 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000720 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000721 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000722 printSimpleInstruction("add");
723 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000724 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000725 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000726 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000727 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000728 }
729 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000730 if (!isZeroValue(IndexValue)) {
731 // Constant optimization.
732 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
733 if (C->getValue().isNegative()) {
734 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
735 printSimpleInstruction("sub");
736 continue;
737 } else
738 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000739 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000740 printPtrLoad(Size);
741 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000742 printSimpleInstruction("mul");
743 }
744 printSimpleInstruction("add");
745 }
746 }
747}
748
749
750std::string MSILWriter::getCallSignature(const FunctionType* Ty,
751 const Instruction* Inst,
752 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000753 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000754 if (Ty->isVarArg()) Tmp += "vararg ";
755 // Name and return type.
756 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
757 // Function argument type list.
758 unsigned NumParams = Ty->getNumParams();
759 for (unsigned I = 0; I!=NumParams; ++I) {
760 if (I!=0) Tmp += ",";
761 Tmp += getTypeName(Ty->getParamType(I));
762 }
763 // CLR needs to know the exact amount of parameters received by vararg
764 // function, because caller cleans the stack.
765 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000766 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000767 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
768 // Print variable argument types.
769 unsigned NumOperands = Inst->getNumOperands()-Org;
770 if (NumParams<NumOperands) {
771 if (NumParams!=0) Tmp += ", ";
772 Tmp += "... , ";
773 for (unsigned J = NumParams; J!=NumOperands; ++J) {
774 if (J!=NumParams) Tmp += ", ";
775 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
776 }
777 }
778 }
779 return Tmp+")";
780}
781
782
783void MSILWriter::printFunctionCall(const Value* FnVal,
784 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000785 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000786 std::string Name = "";
787 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
788 Name = getConvModopt(Call->getCallingConv());
789 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
790 Name = getConvModopt(Invoke->getCallingConv());
791 else {
792 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000793 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000794 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000795 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000796 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000797 Name += getValueName(F);
798 printSimpleInstruction("call",
799 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
800 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000801 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000802 const PointerType* PTy = cast<PointerType>(FnVal->getType());
803 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000804 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000805 printValueLoad(FnVal);
806 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
807 }
808}
809
810
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000811void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
812 std::string Name;
813 switch (Inst->getIntrinsicID()) {
814 case Intrinsic::vastart:
815 Name = getValueName(Inst->getOperand(1));
816 Name.insert(Name.length()-1,"$valist");
817 // Obtain the argument handle.
818 printSimpleInstruction("ldloca",Name.c_str());
819 printSimpleInstruction("arglist");
820 printSimpleInstruction("call",
821 "instance void [mscorlib]System.ArgIterator::.ctor"
822 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
823 // Save as pointer type "void*"
824 printValueLoad(Inst->getOperand(1));
825 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000826 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000827 break;
828 case Intrinsic::vaend:
829 // Close argument list handle.
830 printIndirectLoad(Inst->getOperand(1));
831 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
832 break;
833 case Intrinsic::vacopy:
834 // Copy "ArgIterator" valuetype.
835 printIndirectLoad(Inst->getOperand(1));
836 printIndirectLoad(Inst->getOperand(2));
837 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
838 break;
839 default:
840 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000841 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000842 }
843}
844
845
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000846void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000847 if (isa<IntrinsicInst>(Inst)) {
848 // Handle intrinsic function.
849 printIntrinsicCall(cast<IntrinsicInst>(Inst));
850 } else {
851 // Load arguments to stack and call function.
852 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
853 printValueLoad(Inst->getOperand(I));
854 printFunctionCall(Inst->getOperand(0),Inst);
855 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000856}
857
858
859void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
860 const Value* Right) {
861 switch (Predicate) {
862 case ICmpInst::ICMP_EQ:
863 printBinaryInstruction("ceq",Left,Right);
864 break;
865 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000866 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000867 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000868 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000869 printSimpleInstruction("not");
870 break;
871 case ICmpInst::ICMP_ULE:
872 case ICmpInst::ICMP_SLE:
873 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
874 printBinaryInstruction("ceq",Left,Right);
875 if (Predicate==ICmpInst::ICMP_ULE)
876 printBinaryInstruction("clt.un",Left,Right);
877 else
878 printBinaryInstruction("clt",Left,Right);
879 printSimpleInstruction("or");
880 break;
881 case ICmpInst::ICMP_UGE:
882 case ICmpInst::ICMP_SGE:
883 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
884 printBinaryInstruction("ceq",Left,Right);
885 if (Predicate==ICmpInst::ICMP_UGE)
886 printBinaryInstruction("cgt.un",Left,Right);
887 else
888 printBinaryInstruction("cgt",Left,Right);
889 printSimpleInstruction("or");
890 break;
891 case ICmpInst::ICMP_ULT:
892 printBinaryInstruction("clt.un",Left,Right);
893 break;
894 case ICmpInst::ICMP_SLT:
895 printBinaryInstruction("clt",Left,Right);
896 break;
897 case ICmpInst::ICMP_UGT:
898 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000899 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000900 case ICmpInst::ICMP_SGT:
901 printBinaryInstruction("cgt",Left,Right);
902 break;
903 default:
904 cerr << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000905 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000906 }
907}
908
909
910void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
911 const Value* Right) {
912 // FIXME: Correct comparison
913 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
914 switch (Predicate) {
915 case FCmpInst::FCMP_UGT:
916 // X > Y || llvm_fcmp_uno(X, Y)
917 printBinaryInstruction("cgt",Left,Right);
918 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
919 printSimpleInstruction("or");
920 break;
921 case FCmpInst::FCMP_OGT:
922 // X > Y
923 printBinaryInstruction("cgt",Left,Right);
924 break;
925 case FCmpInst::FCMP_UGE:
926 // X >= Y || llvm_fcmp_uno(X, Y)
927 printBinaryInstruction("ceq",Left,Right);
928 printBinaryInstruction("cgt",Left,Right);
929 printSimpleInstruction("or");
930 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
931 printSimpleInstruction("or");
932 break;
933 case FCmpInst::FCMP_OGE:
934 // X >= Y
935 printBinaryInstruction("ceq",Left,Right);
936 printBinaryInstruction("cgt",Left,Right);
937 printSimpleInstruction("or");
938 break;
939 case FCmpInst::FCMP_ULT:
940 // X < Y || llvm_fcmp_uno(X, Y)
941 printBinaryInstruction("clt",Left,Right);
942 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
943 printSimpleInstruction("or");
944 break;
945 case FCmpInst::FCMP_OLT:
946 // X < Y
947 printBinaryInstruction("clt",Left,Right);
948 break;
949 case FCmpInst::FCMP_ULE:
950 // X <= Y || llvm_fcmp_uno(X, Y)
951 printBinaryInstruction("ceq",Left,Right);
952 printBinaryInstruction("clt",Left,Right);
953 printSimpleInstruction("or");
954 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
955 printSimpleInstruction("or");
956 break;
957 case FCmpInst::FCMP_OLE:
958 // X <= Y
959 printBinaryInstruction("ceq",Left,Right);
960 printBinaryInstruction("clt",Left,Right);
961 printSimpleInstruction("or");
962 break;
963 case FCmpInst::FCMP_UEQ:
964 // X == Y || llvm_fcmp_uno(X, Y)
965 printBinaryInstruction("ceq",Left,Right);
966 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
967 printSimpleInstruction("or");
968 break;
969 case FCmpInst::FCMP_OEQ:
970 // X == Y
971 printBinaryInstruction("ceq",Left,Right);
972 break;
973 case FCmpInst::FCMP_UNE:
974 // X != Y
975 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000976 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000977 printSimpleInstruction("not");
978 break;
979 case FCmpInst::FCMP_ONE:
980 // X != Y && llvm_fcmp_ord(X, Y)
981 printBinaryInstruction("ceq",Left,Right);
982 printSimpleInstruction("not");
983 break;
984 case FCmpInst::FCMP_ORD:
985 // return X == X && Y == Y
986 printBinaryInstruction("ceq",Left,Left);
987 printBinaryInstruction("ceq",Right,Right);
988 printSimpleInstruction("or");
989 break;
990 case FCmpInst::FCMP_UNO:
991 // X != X || Y != Y
992 printBinaryInstruction("ceq",Left,Left);
993 printSimpleInstruction("not");
994 printBinaryInstruction("ceq",Right,Right);
995 printSimpleInstruction("not");
996 printSimpleInstruction("or");
997 break;
998 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000999 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001000 }
1001}
1002
1003
1004void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1005 std::string Label = "leave$normal_"+utostr(getUniqID());
1006 Out << ".try {\n";
1007 // Load arguments
1008 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1009 printValueLoad(Inst->getOperand(I));
1010 // Print call instruction
1011 printFunctionCall(Inst->getOperand(0),Inst);
1012 // Save function result and leave "try" block
1013 printValueSave(Inst);
1014 printSimpleInstruction("leave",Label.c_str());
1015 Out << "}\n";
1016 Out << "catch [mscorlib]System.Exception {\n";
1017 // Redirect to unwind block
1018 printSimpleInstruction("pop");
1019 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1020 Out << "}\n" << Label << ":\n";
1021 // Redirect to continue block
1022 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1023}
1024
1025
1026void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1027 // FIXME: Emulate with IL "switch" instruction
1028 // Emulate = if () else if () else if () else ...
1029 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1030 printValueLoad(Inst->getCondition());
1031 printValueLoad(Inst->getCaseValue(I));
1032 printSimpleInstruction("ceq");
1033 // Condition jump to successor block
1034 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1035 }
1036 // Jump to default block
1037 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1038}
1039
1040
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001041void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1042 printIndirectLoad(Inst->getOperand(0));
1043 printSimpleInstruction("call",
1044 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1045 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001046 std::string Name =
1047 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001048 printSimpleInstruction(Name.c_str());
1049}
1050
1051
1052void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001053 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001054 // Constant optimization.
1055 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1056 printPtrLoad(CInt->getZExtValue()*Size);
1057 } else {
1058 printPtrLoad(Size);
1059 printValueLoad(Inst->getOperand(0));
1060 printSimpleInstruction("mul");
1061 }
1062 printSimpleInstruction("localloc");
1063}
1064
1065
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001066void MSILWriter::printInstruction(const Instruction* Inst) {
1067 const Value *Left = 0, *Right = 0;
1068 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1069 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1070 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001071 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001072 switch (Inst->getOpcode()) {
1073 // Terminator
1074 case Instruction::Ret:
1075 if (Inst->getNumOperands()) {
1076 printValueLoad(Left);
1077 printSimpleInstruction("ret");
1078 } else
1079 printSimpleInstruction("ret");
1080 break;
1081 case Instruction::Br:
1082 printBranchInstruction(cast<BranchInst>(Inst));
1083 break;
1084 // Binary
1085 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001086 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001087 printBinaryInstruction("add",Left,Right);
1088 break;
1089 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001090 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001091 printBinaryInstruction("sub",Left,Right);
1092 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001093 case Instruction::Mul:
1094 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001095 printBinaryInstruction("mul",Left,Right);
1096 break;
1097 case Instruction::UDiv:
1098 printBinaryInstruction("div.un",Left,Right);
1099 break;
1100 case Instruction::SDiv:
1101 case Instruction::FDiv:
1102 printBinaryInstruction("div",Left,Right);
1103 break;
1104 case Instruction::URem:
1105 printBinaryInstruction("rem.un",Left,Right);
1106 break;
1107 case Instruction::SRem:
1108 case Instruction::FRem:
1109 printBinaryInstruction("rem",Left,Right);
1110 break;
1111 // Binary Condition
1112 case Instruction::ICmp:
1113 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1114 break;
1115 case Instruction::FCmp:
1116 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1117 break;
1118 // Bitwise Binary
1119 case Instruction::And:
1120 printBinaryInstruction("and",Left,Right);
1121 break;
1122 case Instruction::Or:
1123 printBinaryInstruction("or",Left,Right);
1124 break;
1125 case Instruction::Xor:
1126 printBinaryInstruction("xor",Left,Right);
1127 break;
1128 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001129 printValueLoad(Left);
1130 printValueLoad(Right);
1131 printSimpleInstruction("conv.i4");
1132 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001133 break;
1134 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001135 printValueLoad(Left);
1136 printValueLoad(Right);
1137 printSimpleInstruction("conv.i4");
1138 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001139 break;
1140 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001141 printValueLoad(Left);
1142 printValueLoad(Right);
1143 printSimpleInstruction("conv.i4");
1144 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001145 break;
1146 case Instruction::Select:
1147 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1148 break;
1149 case Instruction::Load:
1150 printIndirectLoad(Inst->getOperand(0));
1151 break;
1152 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001153 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001154 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001155 case Instruction::SExt:
1156 printCastInstruction(Inst->getOpcode(),Left,
1157 cast<CastInst>(Inst)->getDestTy(),
1158 cast<CastInst>(Inst)->getSrcTy());
1159 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001160 case Instruction::Trunc:
1161 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001162 case Instruction::FPTrunc:
1163 case Instruction::FPExt:
1164 case Instruction::UIToFP:
1165 case Instruction::SIToFP:
1166 case Instruction::FPToUI:
1167 case Instruction::FPToSI:
1168 case Instruction::PtrToInt:
1169 case Instruction::IntToPtr:
1170 case Instruction::BitCast:
1171 printCastInstruction(Inst->getOpcode(),Left,
1172 cast<CastInst>(Inst)->getDestTy());
1173 break;
1174 case Instruction::GetElementPtr:
1175 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1176 gep_type_end(Inst));
1177 break;
1178 case Instruction::Call:
1179 printCallInstruction(cast<CallInst>(Inst));
1180 break;
1181 case Instruction::Invoke:
1182 printInvokeInstruction(cast<InvokeInst>(Inst));
1183 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001184 case Instruction::Unwind:
1185 printSimpleInstruction("newobj",
1186 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001187 printSimpleInstruction("throw");
1188 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001189 case Instruction::Switch:
1190 printSwitchInstruction(cast<SwitchInst>(Inst));
1191 break;
1192 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001193 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001194 break;
1195 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001196 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001197 break;
1198 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001199 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001200 break;
1201 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001202 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1203 printSimpleInstruction("newobj",
1204 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001205 printSimpleInstruction("throw");
1206 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001207 case Instruction::VAArg:
1208 printVAArgInstruction(cast<VAArgInst>(Inst));
1209 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001210 default:
1211 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001212 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001213 }
1214}
1215
1216
1217void MSILWriter::printLoop(const Loop* L) {
1218 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1219 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1220 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1221 BasicBlock* BB = blocks[I];
1222 Loop* BBLoop = LInfo->getLoopFor(BB);
1223 if (BBLoop == L)
1224 printBasicBlock(BB);
1225 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1226 printLoop(BBLoop);
1227 }
1228 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1229}
1230
1231
1232void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1233 Out << getLabelName(BB) << ":\n";
1234 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1235 const Instruction* Inst = I;
1236 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001237 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001238 // Do not handle PHI instruction in current block
1239 if (Inst->getOpcode()==Instruction::PHI) continue;
1240 // Print instruction
1241 printInstruction(Inst);
1242 // Save result
1243 if (Inst->getType()!=Type::VoidTy) {
1244 // Do not save value after invoke, it done in "try" block
1245 if (Inst->getOpcode()==Instruction::Invoke) continue;
1246 printValueSave(Inst);
1247 }
1248 }
1249}
1250
1251
1252void MSILWriter::printLocalVariables(const Function& F) {
1253 std::string Name;
1254 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001255 std::set<const Value*> Printed;
1256 const Value* VaList = NULL;
1257 unsigned StackDepth = 8;
1258 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001259 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001260 if (I->getOpcode()==Instruction::Call ||
1261 I->getOpcode()==Instruction::Invoke) {
1262 // Test stack depth.
1263 if (StackDepth<I->getNumOperands())
1264 StackDepth = I->getNumOperands();
1265 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001266 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1267 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001268 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001269 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001270 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001271 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001272 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001273 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001274 Ty = I->getType();
1275 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001276 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1277 }
1278 // Test on 'va_list' variable
1279 bool isVaList = false;
1280 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1281 // "va_list" as "va_arg" instruction operand.
1282 isVaList = true;
1283 VaList = VaInst->getOperand(0);
1284 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1285 // "va_list" as intrinsic function operand.
1286 switch (Inst->getIntrinsicID()) {
1287 case Intrinsic::vastart:
1288 case Intrinsic::vaend:
1289 case Intrinsic::vacopy:
1290 isVaList = true;
1291 VaList = Inst->getOperand(1);
1292 break;
1293 default:
1294 isVaList = false;
1295 }
1296 }
1297 // Print "va_list" variable.
1298 if (isVaList && Printed.insert(VaList).second) {
1299 Name = getValueName(VaList);
1300 Name.insert(Name.length()-1,"$valist");
1301 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1302 << Name << ")\n";
1303 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001304 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001305 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001306}
1307
1308
1309void MSILWriter::printFunctionBody(const Function& F) {
1310 // Print body
1311 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1312 if (Loop *L = LInfo->getLoopFor(I)) {
1313 if (L->getHeader()==I && L->getParentLoop()==0)
1314 printLoop(L);
1315 } else {
1316 printBasicBlock(I);
1317 }
1318 }
1319}
1320
1321
1322void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1323 const Value *left = 0, *right = 0;
1324 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1325 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1326 // Print instruction
1327 switch (CE->getOpcode()) {
1328 case Instruction::Trunc:
1329 case Instruction::ZExt:
1330 case Instruction::SExt:
1331 case Instruction::FPTrunc:
1332 case Instruction::FPExt:
1333 case Instruction::UIToFP:
1334 case Instruction::SIToFP:
1335 case Instruction::FPToUI:
1336 case Instruction::FPToSI:
1337 case Instruction::PtrToInt:
1338 case Instruction::IntToPtr:
1339 case Instruction::BitCast:
1340 printCastInstruction(CE->getOpcode(),left,CE->getType());
1341 break;
1342 case Instruction::GetElementPtr:
1343 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1344 break;
1345 case Instruction::ICmp:
1346 printICmpInstruction(CE->getPredicate(),left,right);
1347 break;
1348 case Instruction::FCmp:
1349 printFCmpInstruction(CE->getPredicate(),left,right);
1350 break;
1351 case Instruction::Select:
1352 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1353 break;
1354 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001355 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001356 printBinaryInstruction("add",left,right);
1357 break;
1358 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001359 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001360 printBinaryInstruction("sub",left,right);
1361 break;
1362 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001363 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001364 printBinaryInstruction("mul",left,right);
1365 break;
1366 case Instruction::UDiv:
1367 printBinaryInstruction("div.un",left,right);
1368 break;
1369 case Instruction::SDiv:
1370 case Instruction::FDiv:
1371 printBinaryInstruction("div",left,right);
1372 break;
1373 case Instruction::URem:
1374 printBinaryInstruction("rem.un",left,right);
1375 break;
1376 case Instruction::SRem:
1377 case Instruction::FRem:
1378 printBinaryInstruction("rem",left,right);
1379 break;
1380 case Instruction::And:
1381 printBinaryInstruction("and",left,right);
1382 break;
1383 case Instruction::Or:
1384 printBinaryInstruction("or",left,right);
1385 break;
1386 case Instruction::Xor:
1387 printBinaryInstruction("xor",left,right);
1388 break;
1389 case Instruction::Shl:
1390 printBinaryInstruction("shl",left,right);
1391 break;
1392 case Instruction::LShr:
1393 printBinaryInstruction("shr.un",left,right);
1394 break;
1395 case Instruction::AShr:
1396 printBinaryInstruction("shr",left,right);
1397 break;
1398 default:
1399 cerr << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001400 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001401 }
1402}
1403
1404
1405void MSILWriter::printStaticInitializerList() {
1406 // List of global variables with uninitialized fields.
1407 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1408 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1409 ++VarI) {
1410 const std::vector<StaticInitializer>& InitList = VarI->second;
1411 if (InitList.empty()) continue;
1412 // For each uninitialized field.
1413 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1414 E = InitList.end(); I!=E; ++I) {
1415 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001416 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1417 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001418 // Load variable address
1419 printValueLoad(VarI->first);
1420 // Add offset
1421 if (I->offset!=0) {
1422 printPtrLoad(I->offset);
1423 printSimpleInstruction("add");
1424 }
1425 // Load value
1426 printConstantExpr(CE);
1427 // Save result at offset
1428 std::string postfix = getTypePostfix(CE->getType(),true);
1429 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1430 postfix = "stind."+postfix;
1431 printSimpleInstruction(postfix.c_str());
1432 } else {
1433 cerr << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001434 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001435 }
1436 }
1437 }
1438}
1439
1440
1441void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001442 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001443 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001444 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001445 if (F.isVarArg()) Out << "vararg ";
1446 Out << getTypeName(F.getReturnType(),isSigned) <<
1447 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1448 // Arguments
1449 Out << "\t(";
1450 unsigned ArgIdx = 1;
1451 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1452 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001453 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001454 if (I!=F.arg_begin()) Out << ", ";
1455 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1456 }
1457 Out << ") cil managed\n";
1458 // Body
1459 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001460 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001461 printFunctionBody(F);
1462 Out << "}\n";
1463}
1464
1465
1466void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1467 std::string Name;
1468 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001469 for (std::set<const Type*>::const_iterator
1470 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1471 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001472 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1473 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001474 // Type with no need to declare.
1475 else continue;
1476 // Print not duplicated type
1477 if (Printed.insert(Ty).second) {
1478 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001479 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001480 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001481 }
1482 }
1483}
1484
1485
1486unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1487 unsigned int N = Ty->getPrimitiveSizeInBits();
1488 assert(N!=0 && "Invalid type in getBitWidth()");
1489 switch (N) {
1490 case 1:
1491 case 8:
1492 case 16:
1493 case 32:
1494 case 64:
1495 return N;
1496 default:
1497 cerr << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001498 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001499 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001500 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001501}
1502
1503
1504void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1505 uint64_t TySize = 0;
1506 const Type* Ty = C->getType();
1507 // Print zero initialized constant.
1508 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001509 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001510 Offset += TySize;
1511 Out << "int8 (0) [" << TySize << "]";
1512 return;
1513 }
1514 // Print constant initializer
1515 switch (Ty->getTypeID()) {
1516 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001517 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001518 const ConstantInt* Int = cast<ConstantInt>(C);
1519 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1520 break;
1521 }
1522 case Type::FloatTyID:
1523 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001524 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001525 const ConstantFP* FP = cast<ConstantFP>(C);
1526 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001527 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001528 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001529 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001530 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001531 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001532 break;
1533 }
1534 case Type::ArrayTyID:
1535 case Type::VectorTyID:
1536 case Type::StructTyID:
1537 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1538 if (I!=0) Out << ",\n";
1539 printStaticConstant(C->getOperand(I),Offset);
1540 }
1541 break;
1542 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001543 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001544 // Initialize with global variable address
1545 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1546 std::string name = getValueName(G);
1547 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1548 } else {
1549 // Dynamic initialization
1550 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1551 InitListPtr->push_back(StaticInitializer(C,Offset));
1552 // Null pointer initialization
1553 if (TySize==4) Out << "int32 (0)";
1554 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001555 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001556 }
1557 break;
1558 default:
1559 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001560 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001561 }
1562 // Increase offset.
1563 Offset += TySize;
1564}
1565
1566
1567void MSILWriter::printStaticInitializer(const Constant* C,
1568 const std::string& Name) {
1569 switch (C->getType()->getTypeID()) {
1570 case Type::IntegerTyID:
1571 case Type::FloatTyID:
1572 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001573 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001574 break;
1575 case Type::ArrayTyID:
1576 case Type::VectorTyID:
1577 case Type::StructTyID:
1578 case Type::PointerTyID:
1579 Out << getTypeName(C->getType());
1580 break;
1581 default:
1582 cerr << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001583 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001584 }
1585 // Print initializer
1586 std::string label = Name;
1587 label.insert(label.length()-1,"$data");
1588 Out << Name << " at " << label << '\n';
1589 Out << ".data " << label << " = {\n";
1590 uint64_t offset = 0;
1591 printStaticConstant(C,offset);
1592 Out << "\n}\n\n";
1593}
1594
1595
1596void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1597 const Constant* C = G->getInitializer();
1598 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1599 InitListPtr = 0;
1600 else
1601 InitListPtr = &StaticInitList[G];
1602 printStaticInitializer(C,getValueName(G));
1603}
1604
1605
1606void MSILWriter::printGlobalVariables() {
1607 if (ModulePtr->global_empty()) return;
1608 Module::global_iterator I,E;
1609 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1610 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001611 Out << ".field static " << (I->isDeclaration() ? "public " :
1612 "private ");
1613 if (I->isDeclaration()) {
1614 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1615 } else
1616 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001617 }
1618}
1619
1620
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001621const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001622 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001623}
1624
1625
1626const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001627 return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001628}
1629
1630
Daniel Dunbarbda96532009-07-21 08:57:31 +00001631const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1632 bool isFunction,
1633 unsigned CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001634 // TODO: Read *.def file with function and libraries definitions.
1635 return "MSVCRT.DLL";
1636}
1637
1638
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001639void MSILWriter::printExternals() {
1640 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001641 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001642 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1643 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001644 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001645 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001646 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001647 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001648 std::string Sig =
1649 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1650 Out << ".method static hidebysig pinvokeimpl(\""
1651 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001652 }
1653 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001654 // External variables and static initialization.
1655 Out <<
1656 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1657 " native int LoadLibrary(string) preservesig {}\n"
1658 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1659 " native int GetProcAddress(native int, string) preservesig {}\n";
1660 Out <<
1661 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1662 " managed cil\n{\n"
1663 "\tldarg\tlib\n"
1664 "\tcall\tnative int LoadLibrary(string)\n"
1665 "\tldarg\tsym\n"
1666 "\tcall\tnative int GetProcAddress(native int,string)\n"
1667 "\tdup\n"
1668 "\tbrtrue\tL_01\n"
1669 "\tldstr\t\"Can no import variable\"\n"
1670 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1671 "\tthrow\n"
1672 "L_01:\n"
1673 "\tret\n"
1674 "}\n\n"
1675 ".method static private void $MSIL_Init() managed cil\n{\n";
1676 printStaticInitializerList();
1677 // Foreach global variable.
1678 for (Module::global_iterator I = ModulePtr->global_begin(),
1679 E = ModulePtr->global_end(); I!=E; ++I) {
1680 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1681 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1682 std::string Label = "not_null$_"+utostr(getUniqID());
1683 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1684 printSimpleInstruction("ldsflda",Tmp.c_str());
1685 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001686 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001687 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1688 printIndirectSave(I->getType());
1689 }
1690 printSimpleInstruction("ret");
1691 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001692}
1693
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001694
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001695//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001696// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001697//===----------------------------------------------------------------------===//
1698
David Greene71847812009-07-14 20:18:05 +00001699bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1700 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001701 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001702 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001703{
1704 if (FileType != TargetMachine::AssemblyFile) return true;
1705 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001706 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001707 PM.add(createLowerAllocationsPass(true));
1708 // FIXME: Handle switch trougth native IL instruction "switch"
1709 PM.add(createLowerSwitchPass());
1710 PM.add(createCFGSimplificationPass());
1711 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1712 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001713 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001714 return false;
1715}