blob: dbfcdb7207bff90d17718b08587ff905a81a88fb [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 +000050extern Target TheMSILTarget;
51static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000052
Bob Wilsona96751f2009-06-23 23:59:40 +000053// Force static initialization.
54extern "C" void LLVMInitializeMSILTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000055
Anton Korobeynikov099883f2007-03-21 21:38:25 +000056bool MSILModule::runOnModule(Module &M) {
57 ModulePtr = &M;
58 TD = &getAnalysis<TargetData>();
59 bool Changed = false;
60 // Find named types.
61 TypeSymbolTable& Table = M.getTypeSymbolTable();
62 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
63 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
64 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
65 Table.remove(I++);
66 else {
67 std::set<const Type *>::iterator T = Types.find(I->second);
68 if (T==Types.end())
69 Table.remove(I++);
70 else {
71 Types.erase(T);
72 ++I;
73 }
74 }
75 }
76 // Find unnamed types.
77 unsigned RenameCounter = 0;
78 for (std::set<const Type *>::const_iterator I = Types.begin(),
79 E = Types.end(); I!=E; ++I)
80 if (const StructType *STy = dyn_cast<StructType>(*I)) {
81 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
82 ++RenameCounter;
83 Changed = true;
84 }
85 // Pointer for FunctionPass.
86 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
87 return Changed;
88}
89
Devang Patel19974732007-05-03 01:11:54 +000090char MSILModule::ID = 0;
91char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000092
93bool MSILWriter::runOnFunction(Function &F) {
94 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000095
96 // Do not codegen any 'available_externally' functions at all, they have
97 // definitions outside the translation unit.
98 if (F.hasAvailableExternallyLinkage())
99 return false;
100
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000101 LInfo = &getAnalysis<LoopInfo>();
102 printFunction(F);
103 return false;
104}
105
106
107bool MSILWriter::doInitialization(Module &M) {
108 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000109 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000110 Out << ".assembly extern mscorlib {}\n";
111 Out << ".assembly MSIL {}\n\n";
112 Out << "// External\n";
113 printExternals();
114 Out << "// Declarations\n";
115 printDeclarations(M.getTypeSymbolTable());
116 Out << "// Definitions\n";
117 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000118 Out << "// Startup code\n";
119 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000120 return false;
121}
122
123
124bool MSILWriter::doFinalization(Module &M) {
125 delete Mang;
126 return false;
127}
128
129
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000130void MSILWriter::printModuleStartup() {
131 Out <<
132 ".method static public int32 $MSIL_Startup() {\n"
133 "\t.entrypoint\n"
134 "\t.locals (native int i)\n"
135 "\t.locals (native int argc)\n"
136 "\t.locals (native int ptr)\n"
137 "\t.locals (void* argv)\n"
138 "\t.locals (string[] args)\n"
139 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
140 "\tdup\n"
141 "\tstloc\targs\n"
142 "\tldlen\n"
143 "\tconv.i4\n"
144 "\tdup\n"
145 "\tstloc\targc\n";
146 printPtrLoad(TD->getPointerSize());
147 Out <<
148 "\tmul\n"
149 "\tlocalloc\n"
150 "\tstloc\targv\n"
151 "\tldc.i4.0\n"
152 "\tstloc\ti\n"
153 "L_01:\n"
154 "\tldloc\ti\n"
155 "\tldloc\targc\n"
156 "\tceq\n"
157 "\tbrtrue\tL_02\n"
158 "\tldloc\targs\n"
159 "\tldloc\ti\n"
160 "\tldelem.ref\n"
161 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
162 "StringToHGlobalAnsi(string)\n"
163 "\tstloc\tptr\n"
164 "\tldloc\targv\n"
165 "\tldloc\ti\n";
166 printPtrLoad(TD->getPointerSize());
167 Out <<
168 "\tmul\n"
169 "\tadd\n"
170 "\tldloc\tptr\n"
171 "\tstind.i\n"
172 "\tldloc\ti\n"
173 "\tldc.i4.1\n"
174 "\tadd\n"
175 "\tstloc\ti\n"
176 "\tbr\tL_01\n"
177 "L_02:\n"
178 "\tcall void $MSIL_Init()\n";
179
180 // Call user 'main' function.
181 const Function* F = ModulePtr->getFunction("main");
182 if (!F || F->isDeclaration()) {
183 Out << "\tldc.i4.0\n\tret\n}\n";
184 return;
185 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000186 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000187 std::string Args("");
188 Function::const_arg_iterator Arg1,Arg2;
189
190 switch (F->arg_size()) {
191 case 0:
192 BadSig = false;
193 break;
194 case 1:
195 Arg1 = F->arg_begin();
196 if (Arg1->getType()->isInteger()) {
197 Out << "\tldloc\targc\n";
198 Args = getTypeName(Arg1->getType());
199 BadSig = false;
200 }
201 break;
202 case 2:
203 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
204 if (Arg1->getType()->isInteger() &&
205 Arg2->getType()->getTypeID() == Type::PointerTyID) {
206 Out << "\tldloc\targc\n\tldloc\targv\n";
207 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
208 BadSig = false;
209 }
210 break;
211 default:
212 BadSig = true;
213 }
214
215 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000216 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000217 Out << "\tldc.i4.0\n";
218 } else {
219 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
220 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
221 if (RetVoid)
222 Out << "\tldc.i4.0\n";
223 else
224 Out << "\tconv.i4\n";
225 }
226 Out << "\tret\n}\n";
227}
228
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000229bool MSILWriter::isZeroValue(const Value* V) {
230 if (const Constant *C = dyn_cast<Constant>(V))
231 return C->isNullValue();
232 return false;
233}
234
235
236std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000237 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000238 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000239 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000240 else {
241 unsigned &No = AnonValueNumbers[V];
242 if (No == 0) No = ++NextAnonValueNumber;
243 Name = "tmp" + utostr(No);
244 }
245
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000246 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000247 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000248}
249
250
251std::string MSILWriter::getLabelName(const std::string& Name) {
252 if (Name.find('.')!=std::string::npos) {
253 std::string Tmp(Name);
254 // Replace unaccepable characters in the label name.
255 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
256 if (*I=='.') *I = '@';
257 return Tmp;
258 }
259 return Name;
260}
261
262
263std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000264 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000265 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000266 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000267 else {
268 unsigned &No = AnonValueNumbers[V];
269 if (No == 0) No = ++NextAnonValueNumber;
270 Name = "tmp" + utostr(No);
271 }
272
273 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000274}
275
276
277std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
278 switch (CallingConvID) {
279 case CallingConv::C:
280 case CallingConv::Cold:
281 case CallingConv::Fast:
282 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
283 case CallingConv::X86_FastCall:
284 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
285 case CallingConv::X86_StdCall:
286 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
287 default:
288 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000289 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000290 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000291 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000292}
293
294
295std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
296 std::string Tmp = "";
297 const Type* ElemTy = Ty;
298 assert(Ty->getTypeID()==TyID && "Invalid type passed");
299 // Walk trought array element types.
300 for (;;) {
301 // Multidimensional array.
302 if (ElemTy->getTypeID()==TyID) {
303 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
304 Tmp += utostr(ATy->getNumElements());
305 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
306 Tmp += utostr(VTy->getNumElements());
307 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
308 }
309 // Base element type found.
310 if (ElemTy->getTypeID()!=TyID) break;
311 Tmp += ",";
312 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000313 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000314}
315
316
317std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
318 unsigned NumBits = 0;
319 switch (Ty->getTypeID()) {
320 case Type::VoidTyID:
321 return "void ";
322 case Type::IntegerTyID:
323 NumBits = getBitWidth(Ty);
324 if(NumBits==1)
325 return "bool ";
326 if (!isSigned)
327 return "unsigned int"+utostr(NumBits)+" ";
328 return "int"+utostr(NumBits)+" ";
329 case Type::FloatTyID:
330 return "float32 ";
331 case Type::DoubleTyID:
332 return "float64 ";
333 default:
334 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000335 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000336 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000337 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000338}
339
340
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000341std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
342 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000343 if (Ty->isPrimitiveType() || Ty->isInteger())
344 return getPrimitiveTypeName(Ty,isSigned);
345 // FIXME: "OpaqueType" support
346 switch (Ty->getTypeID()) {
347 case Type::PointerTyID:
348 return "void* ";
349 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000350 if (isNested)
351 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000352 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
353 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000354 if (isNested)
355 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000356 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
357 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000358 if (isNested)
359 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000360 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
361 default:
362 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000363 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000364 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000365 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000366}
367
368
369MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
370 // Function argument
371 if (isa<Argument>(V))
372 return ArgumentVT;
373 // Function
374 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000375 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000376 // Variable
377 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000378 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000379 // Constant
380 else if (isa<Constant>(V))
381 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
382 // Local variable
383 return LocalVT;
384}
385
386
387std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
388 bool isSigned) {
389 unsigned NumBits = 0;
390 switch (Ty->getTypeID()) {
391 // Integer constant, expanding for stack operations.
392 case Type::IntegerTyID:
393 NumBits = getBitWidth(Ty);
394 // Expand integer value to "int32" or "int64".
395 if (Expand) return (NumBits<=32 ? "i4" : "i8");
396 if (NumBits==1) return "i1";
397 return (isSigned ? "i" : "u")+utostr(NumBits/8);
398 // Float constant.
399 case Type::FloatTyID:
400 return "r4";
401 case Type::DoubleTyID:
402 return "r8";
403 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000404 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000405 default:
406 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000407 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000408 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000409 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000410}
411
412
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000413void MSILWriter::printConvToPtr() {
414 switch (ModulePtr->getPointerSize()) {
415 case Module::Pointer32:
416 printSimpleInstruction("conv.u4");
417 break;
418 case Module::Pointer64:
419 printSimpleInstruction("conv.u8");
420 break;
421 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000422 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000423 }
424}
425
426
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000427void MSILWriter::printPtrLoad(uint64_t N) {
428 switch (ModulePtr->getPointerSize()) {
429 case Module::Pointer32:
430 printSimpleInstruction("ldc.i4",utostr(N).c_str());
431 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000432 if (!isUInt32(N)) {
433 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000434 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000435 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000436 break;
437 case Module::Pointer64:
438 printSimpleInstruction("ldc.i8",utostr(N).c_str());
439 break;
440 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000441 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000442 }
443}
444
445
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000446void MSILWriter::printValuePtrLoad(const Value* V) {
447 printValueLoad(V);
448 printConvToPtr();
449}
450
451
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000452void MSILWriter::printConstLoad(const Constant* C) {
453 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
454 // Integer constant
455 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
456 if (CInt->isMinValue(true))
457 Out << CInt->getSExtValue();
458 else
459 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000460 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000461 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000462 uint64_t X;
463 unsigned Size;
464 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000465 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000466 Size = 4;
467 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000468 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000469 Size = 8;
470 }
471 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
472 } else if (isa<UndefValue>(C)) {
473 // Undefined constant value = NULL.
474 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000475 } else {
476 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000477 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000478 }
479 Out << '\n';
480}
481
482
483void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000484 MSILWriter::ValueType Location = getValueLocation(V);
485 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000486 // Global variable or function address.
487 case GlobalVT:
488 case InternalVT:
489 if (const Function* F = dyn_cast<Function>(V)) {
490 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
491 printSimpleInstruction("ldftn",
492 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
493 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000494 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000495 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000496 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
497 Tmp = "void* "+getValueName(V);
498 printSimpleInstruction("ldsfld",Tmp.c_str());
499 } else {
500 Tmp = getTypeName(ElemTy)+getValueName(V);
501 printSimpleInstruction("ldsflda",Tmp.c_str());
502 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000503 }
504 break;
505 // Function argument.
506 case ArgumentVT:
507 printSimpleInstruction("ldarg",getValueName(V).c_str());
508 break;
509 // Local function variable.
510 case LocalVT:
511 printSimpleInstruction("ldloc",getValueName(V).c_str());
512 break;
513 // Constant value.
514 case ConstVT:
515 if (isa<ConstantPointerNull>(V))
516 printPtrLoad(0);
517 else
518 printConstLoad(cast<Constant>(V));
519 break;
520 // Constant expression.
521 case ConstExprVT:
522 printConstantExpr(cast<ConstantExpr>(V));
523 break;
524 default:
525 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000526 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000527 }
528}
529
530
531void MSILWriter::printValueSave(const Value* V) {
532 switch (getValueLocation(V)) {
533 case ArgumentVT:
534 printSimpleInstruction("starg",getValueName(V).c_str());
535 break;
536 case LocalVT:
537 printSimpleInstruction("stloc",getValueName(V).c_str());
538 break;
539 default:
540 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000541 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000542 }
543}
544
545
546void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
547 const Value* Right) {
548 printValueLoad(Left);
549 printValueLoad(Right);
550 Out << '\t' << Name << '\n';
551}
552
553
554void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
555 if(Operand)
556 Out << '\t' << Inst << '\t' << Operand << '\n';
557 else
558 Out << '\t' << Inst << '\n';
559}
560
561
562void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
563 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
564 isa<PHINode>(I); ++I) {
565 const PHINode* Phi = cast<PHINode>(I);
566 const Value* Val = Phi->getIncomingValueForBlock(Src);
567 if (isa<UndefValue>(Val)) continue;
568 printValueLoad(Val);
569 printValueSave(Phi);
570 }
571}
572
573
574void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
575 const BasicBlock* TrueBB,
576 const BasicBlock* FalseBB) {
577 if (TrueBB==FalseBB) {
578 // "TrueBB" and "FalseBB" destination equals
579 printPHICopy(CurrBB,TrueBB);
580 printSimpleInstruction("pop");
581 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
582 } else if (FalseBB==NULL) {
583 // If "FalseBB" not used the jump have condition
584 printPHICopy(CurrBB,TrueBB);
585 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
586 } else if (TrueBB==NULL) {
587 // If "TrueBB" not used the jump is unconditional
588 printPHICopy(CurrBB,FalseBB);
589 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
590 } else {
591 // Copy PHI instructions for each block
592 std::string TmpLabel;
593 // Print PHI instructions for "TrueBB"
594 if (isa<PHINode>(TrueBB->begin())) {
595 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
596 printSimpleInstruction("brtrue",TmpLabel.c_str());
597 } else {
598 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
599 }
600 // Print PHI instructions for "FalseBB"
601 if (isa<PHINode>(FalseBB->begin())) {
602 printPHICopy(CurrBB,FalseBB);
603 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
604 } else {
605 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
606 }
607 if (isa<PHINode>(TrueBB->begin())) {
608 // Handle "TrueBB" PHI Copy
609 Out << TmpLabel << ":\n";
610 printPHICopy(CurrBB,TrueBB);
611 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
612 }
613 }
614}
615
616
617void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
618 if (Inst->isUnconditional()) {
619 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
620 } else {
621 printValueLoad(Inst->getCondition());
622 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
623 Inst->getSuccessor(1));
624 }
625}
626
627
628void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
629 const Value* VFalse) {
630 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
631 printValueLoad(VTrue);
632 printValueLoad(Cond);
633 printSimpleInstruction("brtrue",TmpLabel.c_str());
634 printSimpleInstruction("pop");
635 printValueLoad(VFalse);
636 Out << TmpLabel << ":\n";
637}
638
639
640void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000641 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000642 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000643 if (const PointerType* P = dyn_cast<PointerType>(Ty))
644 Ty = P->getElementType();
645 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000646 printSimpleInstruction(Tmp.c_str());
647}
648
649
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000650void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000651 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000652 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000653 printIndirectSave(Val->getType());
654}
655
656
657void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000658 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000659 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000660 if (*postfix.begin()=='u') *postfix.begin() = 'i';
661 postfix = "stind."+postfix;
662 printSimpleInstruction(postfix.c_str());
663}
664
665
666void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000667 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000668 std::string Tmp("");
669 printValueLoad(V);
670 switch (Op) {
671 // Signed
672 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000673 // If sign extending int, convert first from unsigned to signed
674 // with the same bit size - because otherwise we will loose the sign.
675 if (SrcTy) {
676 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
677 printSimpleInstruction(Tmp.c_str());
678 }
Bill Wendling5f544502009-07-14 18:30:04 +0000679 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000680 case Instruction::SIToFP:
681 case Instruction::FPToSI:
682 Tmp = "conv."+getTypePostfix(Ty,false,true);
683 printSimpleInstruction(Tmp.c_str());
684 break;
685 // Unsigned
686 case Instruction::FPTrunc:
687 case Instruction::FPExt:
688 case Instruction::UIToFP:
689 case Instruction::Trunc:
690 case Instruction::ZExt:
691 case Instruction::FPToUI:
692 case Instruction::PtrToInt:
693 case Instruction::IntToPtr:
694 Tmp = "conv."+getTypePostfix(Ty,false);
695 printSimpleInstruction(Tmp.c_str());
696 break;
697 // Do nothing
698 case Instruction::BitCast:
699 // FIXME: meaning that ld*/st* instruction do not change data format.
700 break;
701 default:
702 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000703 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000704 }
705}
706
707
708void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
709 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000710 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000711 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000712 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000713 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000714 for (; I!=E; ++I){
715 Size = 0;
716 const Value* IndexValue = I.getOperand();
717 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
718 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
719 // Offset is the sum of all previous structure fields.
720 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000721 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000722 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000723 printSimpleInstruction("add");
724 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000725 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000726 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000727 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000728 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000729 }
730 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000731 if (!isZeroValue(IndexValue)) {
732 // Constant optimization.
733 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
734 if (C->getValue().isNegative()) {
735 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
736 printSimpleInstruction("sub");
737 continue;
738 } else
739 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000740 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000741 printPtrLoad(Size);
742 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000743 printSimpleInstruction("mul");
744 }
745 printSimpleInstruction("add");
746 }
747 }
748}
749
750
751std::string MSILWriter::getCallSignature(const FunctionType* Ty,
752 const Instruction* Inst,
753 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000754 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000755 if (Ty->isVarArg()) Tmp += "vararg ";
756 // Name and return type.
757 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
758 // Function argument type list.
759 unsigned NumParams = Ty->getNumParams();
760 for (unsigned I = 0; I!=NumParams; ++I) {
761 if (I!=0) Tmp += ",";
762 Tmp += getTypeName(Ty->getParamType(I));
763 }
764 // CLR needs to know the exact amount of parameters received by vararg
765 // function, because caller cleans the stack.
766 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000767 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000768 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
769 // Print variable argument types.
770 unsigned NumOperands = Inst->getNumOperands()-Org;
771 if (NumParams<NumOperands) {
772 if (NumParams!=0) Tmp += ", ";
773 Tmp += "... , ";
774 for (unsigned J = NumParams; J!=NumOperands; ++J) {
775 if (J!=NumParams) Tmp += ", ";
776 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
777 }
778 }
779 }
780 return Tmp+")";
781}
782
783
784void MSILWriter::printFunctionCall(const Value* FnVal,
785 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000786 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000787 std::string Name = "";
788 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
789 Name = getConvModopt(Call->getCallingConv());
790 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
791 Name = getConvModopt(Invoke->getCallingConv());
792 else {
793 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000794 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000795 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000796 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000797 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000798 Name += getValueName(F);
799 printSimpleInstruction("call",
800 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
801 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000802 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000803 const PointerType* PTy = cast<PointerType>(FnVal->getType());
804 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000805 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000806 printValueLoad(FnVal);
807 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
808 }
809}
810
811
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000812void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
813 std::string Name;
814 switch (Inst->getIntrinsicID()) {
815 case Intrinsic::vastart:
816 Name = getValueName(Inst->getOperand(1));
817 Name.insert(Name.length()-1,"$valist");
818 // Obtain the argument handle.
819 printSimpleInstruction("ldloca",Name.c_str());
820 printSimpleInstruction("arglist");
821 printSimpleInstruction("call",
822 "instance void [mscorlib]System.ArgIterator::.ctor"
823 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
824 // Save as pointer type "void*"
825 printValueLoad(Inst->getOperand(1));
826 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000827 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000828 break;
829 case Intrinsic::vaend:
830 // Close argument list handle.
831 printIndirectLoad(Inst->getOperand(1));
832 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
833 break;
834 case Intrinsic::vacopy:
835 // Copy "ArgIterator" valuetype.
836 printIndirectLoad(Inst->getOperand(1));
837 printIndirectLoad(Inst->getOperand(2));
838 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
839 break;
840 default:
841 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000842 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000843 }
844}
845
846
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000847void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000848 if (isa<IntrinsicInst>(Inst)) {
849 // Handle intrinsic function.
850 printIntrinsicCall(cast<IntrinsicInst>(Inst));
851 } else {
852 // Load arguments to stack and call function.
853 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
854 printValueLoad(Inst->getOperand(I));
855 printFunctionCall(Inst->getOperand(0),Inst);
856 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000857}
858
859
860void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
861 const Value* Right) {
862 switch (Predicate) {
863 case ICmpInst::ICMP_EQ:
864 printBinaryInstruction("ceq",Left,Right);
865 break;
866 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000867 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000868 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000869 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000870 printSimpleInstruction("not");
871 break;
872 case ICmpInst::ICMP_ULE:
873 case ICmpInst::ICMP_SLE:
874 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
875 printBinaryInstruction("ceq",Left,Right);
876 if (Predicate==ICmpInst::ICMP_ULE)
877 printBinaryInstruction("clt.un",Left,Right);
878 else
879 printBinaryInstruction("clt",Left,Right);
880 printSimpleInstruction("or");
881 break;
882 case ICmpInst::ICMP_UGE:
883 case ICmpInst::ICMP_SGE:
884 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
885 printBinaryInstruction("ceq",Left,Right);
886 if (Predicate==ICmpInst::ICMP_UGE)
887 printBinaryInstruction("cgt.un",Left,Right);
888 else
889 printBinaryInstruction("cgt",Left,Right);
890 printSimpleInstruction("or");
891 break;
892 case ICmpInst::ICMP_ULT:
893 printBinaryInstruction("clt.un",Left,Right);
894 break;
895 case ICmpInst::ICMP_SLT:
896 printBinaryInstruction("clt",Left,Right);
897 break;
898 case ICmpInst::ICMP_UGT:
899 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000900 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000901 case ICmpInst::ICMP_SGT:
902 printBinaryInstruction("cgt",Left,Right);
903 break;
904 default:
905 cerr << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000906 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000907 }
908}
909
910
911void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
912 const Value* Right) {
913 // FIXME: Correct comparison
914 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
915 switch (Predicate) {
916 case FCmpInst::FCMP_UGT:
917 // X > Y || llvm_fcmp_uno(X, Y)
918 printBinaryInstruction("cgt",Left,Right);
919 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
920 printSimpleInstruction("or");
921 break;
922 case FCmpInst::FCMP_OGT:
923 // X > Y
924 printBinaryInstruction("cgt",Left,Right);
925 break;
926 case FCmpInst::FCMP_UGE:
927 // X >= Y || llvm_fcmp_uno(X, Y)
928 printBinaryInstruction("ceq",Left,Right);
929 printBinaryInstruction("cgt",Left,Right);
930 printSimpleInstruction("or");
931 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
932 printSimpleInstruction("or");
933 break;
934 case FCmpInst::FCMP_OGE:
935 // X >= Y
936 printBinaryInstruction("ceq",Left,Right);
937 printBinaryInstruction("cgt",Left,Right);
938 printSimpleInstruction("or");
939 break;
940 case FCmpInst::FCMP_ULT:
941 // X < Y || llvm_fcmp_uno(X, Y)
942 printBinaryInstruction("clt",Left,Right);
943 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
944 printSimpleInstruction("or");
945 break;
946 case FCmpInst::FCMP_OLT:
947 // X < Y
948 printBinaryInstruction("clt",Left,Right);
949 break;
950 case FCmpInst::FCMP_ULE:
951 // X <= Y || llvm_fcmp_uno(X, Y)
952 printBinaryInstruction("ceq",Left,Right);
953 printBinaryInstruction("clt",Left,Right);
954 printSimpleInstruction("or");
955 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
956 printSimpleInstruction("or");
957 break;
958 case FCmpInst::FCMP_OLE:
959 // X <= Y
960 printBinaryInstruction("ceq",Left,Right);
961 printBinaryInstruction("clt",Left,Right);
962 printSimpleInstruction("or");
963 break;
964 case FCmpInst::FCMP_UEQ:
965 // X == Y || llvm_fcmp_uno(X, Y)
966 printBinaryInstruction("ceq",Left,Right);
967 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
968 printSimpleInstruction("or");
969 break;
970 case FCmpInst::FCMP_OEQ:
971 // X == Y
972 printBinaryInstruction("ceq",Left,Right);
973 break;
974 case FCmpInst::FCMP_UNE:
975 // X != Y
976 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000977 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000978 printSimpleInstruction("not");
979 break;
980 case FCmpInst::FCMP_ONE:
981 // X != Y && llvm_fcmp_ord(X, Y)
982 printBinaryInstruction("ceq",Left,Right);
983 printSimpleInstruction("not");
984 break;
985 case FCmpInst::FCMP_ORD:
986 // return X == X && Y == Y
987 printBinaryInstruction("ceq",Left,Left);
988 printBinaryInstruction("ceq",Right,Right);
989 printSimpleInstruction("or");
990 break;
991 case FCmpInst::FCMP_UNO:
992 // X != X || Y != Y
993 printBinaryInstruction("ceq",Left,Left);
994 printSimpleInstruction("not");
995 printBinaryInstruction("ceq",Right,Right);
996 printSimpleInstruction("not");
997 printSimpleInstruction("or");
998 break;
999 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001000 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001001 }
1002}
1003
1004
1005void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1006 std::string Label = "leave$normal_"+utostr(getUniqID());
1007 Out << ".try {\n";
1008 // Load arguments
1009 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1010 printValueLoad(Inst->getOperand(I));
1011 // Print call instruction
1012 printFunctionCall(Inst->getOperand(0),Inst);
1013 // Save function result and leave "try" block
1014 printValueSave(Inst);
1015 printSimpleInstruction("leave",Label.c_str());
1016 Out << "}\n";
1017 Out << "catch [mscorlib]System.Exception {\n";
1018 // Redirect to unwind block
1019 printSimpleInstruction("pop");
1020 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1021 Out << "}\n" << Label << ":\n";
1022 // Redirect to continue block
1023 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1024}
1025
1026
1027void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1028 // FIXME: Emulate with IL "switch" instruction
1029 // Emulate = if () else if () else if () else ...
1030 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1031 printValueLoad(Inst->getCondition());
1032 printValueLoad(Inst->getCaseValue(I));
1033 printSimpleInstruction("ceq");
1034 // Condition jump to successor block
1035 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1036 }
1037 // Jump to default block
1038 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1039}
1040
1041
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001042void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1043 printIndirectLoad(Inst->getOperand(0));
1044 printSimpleInstruction("call",
1045 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1046 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001047 std::string Name =
1048 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001049 printSimpleInstruction(Name.c_str());
1050}
1051
1052
1053void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001054 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001055 // Constant optimization.
1056 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1057 printPtrLoad(CInt->getZExtValue()*Size);
1058 } else {
1059 printPtrLoad(Size);
1060 printValueLoad(Inst->getOperand(0));
1061 printSimpleInstruction("mul");
1062 }
1063 printSimpleInstruction("localloc");
1064}
1065
1066
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001067void MSILWriter::printInstruction(const Instruction* Inst) {
1068 const Value *Left = 0, *Right = 0;
1069 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1070 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1071 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001072 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001073 switch (Inst->getOpcode()) {
1074 // Terminator
1075 case Instruction::Ret:
1076 if (Inst->getNumOperands()) {
1077 printValueLoad(Left);
1078 printSimpleInstruction("ret");
1079 } else
1080 printSimpleInstruction("ret");
1081 break;
1082 case Instruction::Br:
1083 printBranchInstruction(cast<BranchInst>(Inst));
1084 break;
1085 // Binary
1086 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001087 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001088 printBinaryInstruction("add",Left,Right);
1089 break;
1090 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001091 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001092 printBinaryInstruction("sub",Left,Right);
1093 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001094 case Instruction::Mul:
1095 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001096 printBinaryInstruction("mul",Left,Right);
1097 break;
1098 case Instruction::UDiv:
1099 printBinaryInstruction("div.un",Left,Right);
1100 break;
1101 case Instruction::SDiv:
1102 case Instruction::FDiv:
1103 printBinaryInstruction("div",Left,Right);
1104 break;
1105 case Instruction::URem:
1106 printBinaryInstruction("rem.un",Left,Right);
1107 break;
1108 case Instruction::SRem:
1109 case Instruction::FRem:
1110 printBinaryInstruction("rem",Left,Right);
1111 break;
1112 // Binary Condition
1113 case Instruction::ICmp:
1114 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1115 break;
1116 case Instruction::FCmp:
1117 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1118 break;
1119 // Bitwise Binary
1120 case Instruction::And:
1121 printBinaryInstruction("and",Left,Right);
1122 break;
1123 case Instruction::Or:
1124 printBinaryInstruction("or",Left,Right);
1125 break;
1126 case Instruction::Xor:
1127 printBinaryInstruction("xor",Left,Right);
1128 break;
1129 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001130 printValueLoad(Left);
1131 printValueLoad(Right);
1132 printSimpleInstruction("conv.i4");
1133 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001134 break;
1135 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001136 printValueLoad(Left);
1137 printValueLoad(Right);
1138 printSimpleInstruction("conv.i4");
1139 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001140 break;
1141 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001142 printValueLoad(Left);
1143 printValueLoad(Right);
1144 printSimpleInstruction("conv.i4");
1145 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001146 break;
1147 case Instruction::Select:
1148 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1149 break;
1150 case Instruction::Load:
1151 printIndirectLoad(Inst->getOperand(0));
1152 break;
1153 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001154 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001155 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001156 case Instruction::SExt:
1157 printCastInstruction(Inst->getOpcode(),Left,
1158 cast<CastInst>(Inst)->getDestTy(),
1159 cast<CastInst>(Inst)->getSrcTy());
1160 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001161 case Instruction::Trunc:
1162 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001163 case Instruction::FPTrunc:
1164 case Instruction::FPExt:
1165 case Instruction::UIToFP:
1166 case Instruction::SIToFP:
1167 case Instruction::FPToUI:
1168 case Instruction::FPToSI:
1169 case Instruction::PtrToInt:
1170 case Instruction::IntToPtr:
1171 case Instruction::BitCast:
1172 printCastInstruction(Inst->getOpcode(),Left,
1173 cast<CastInst>(Inst)->getDestTy());
1174 break;
1175 case Instruction::GetElementPtr:
1176 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1177 gep_type_end(Inst));
1178 break;
1179 case Instruction::Call:
1180 printCallInstruction(cast<CallInst>(Inst));
1181 break;
1182 case Instruction::Invoke:
1183 printInvokeInstruction(cast<InvokeInst>(Inst));
1184 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001185 case Instruction::Unwind:
1186 printSimpleInstruction("newobj",
1187 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001188 printSimpleInstruction("throw");
1189 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001190 case Instruction::Switch:
1191 printSwitchInstruction(cast<SwitchInst>(Inst));
1192 break;
1193 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001194 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001195 break;
1196 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001197 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001198 break;
1199 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001200 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001201 break;
1202 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001203 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1204 printSimpleInstruction("newobj",
1205 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001206 printSimpleInstruction("throw");
1207 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001208 case Instruction::VAArg:
1209 printVAArgInstruction(cast<VAArgInst>(Inst));
1210 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001211 default:
1212 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001213 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001214 }
1215}
1216
1217
1218void MSILWriter::printLoop(const Loop* L) {
1219 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1220 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1221 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1222 BasicBlock* BB = blocks[I];
1223 Loop* BBLoop = LInfo->getLoopFor(BB);
1224 if (BBLoop == L)
1225 printBasicBlock(BB);
1226 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1227 printLoop(BBLoop);
1228 }
1229 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1230}
1231
1232
1233void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1234 Out << getLabelName(BB) << ":\n";
1235 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1236 const Instruction* Inst = I;
1237 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001238 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001239 // Do not handle PHI instruction in current block
1240 if (Inst->getOpcode()==Instruction::PHI) continue;
1241 // Print instruction
1242 printInstruction(Inst);
1243 // Save result
1244 if (Inst->getType()!=Type::VoidTy) {
1245 // Do not save value after invoke, it done in "try" block
1246 if (Inst->getOpcode()==Instruction::Invoke) continue;
1247 printValueSave(Inst);
1248 }
1249 }
1250}
1251
1252
1253void MSILWriter::printLocalVariables(const Function& F) {
1254 std::string Name;
1255 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001256 std::set<const Value*> Printed;
1257 const Value* VaList = NULL;
1258 unsigned StackDepth = 8;
1259 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001260 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001261 if (I->getOpcode()==Instruction::Call ||
1262 I->getOpcode()==Instruction::Invoke) {
1263 // Test stack depth.
1264 if (StackDepth<I->getNumOperands())
1265 StackDepth = I->getNumOperands();
1266 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001267 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1268 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001269 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001270 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001271 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001272 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001273 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001274 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001275 Ty = I->getType();
1276 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001277 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1278 }
1279 // Test on 'va_list' variable
1280 bool isVaList = false;
1281 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1282 // "va_list" as "va_arg" instruction operand.
1283 isVaList = true;
1284 VaList = VaInst->getOperand(0);
1285 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1286 // "va_list" as intrinsic function operand.
1287 switch (Inst->getIntrinsicID()) {
1288 case Intrinsic::vastart:
1289 case Intrinsic::vaend:
1290 case Intrinsic::vacopy:
1291 isVaList = true;
1292 VaList = Inst->getOperand(1);
1293 break;
1294 default:
1295 isVaList = false;
1296 }
1297 }
1298 // Print "va_list" variable.
1299 if (isVaList && Printed.insert(VaList).second) {
1300 Name = getValueName(VaList);
1301 Name.insert(Name.length()-1,"$valist");
1302 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1303 << Name << ")\n";
1304 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001305 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001306 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001307}
1308
1309
1310void MSILWriter::printFunctionBody(const Function& F) {
1311 // Print body
1312 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1313 if (Loop *L = LInfo->getLoopFor(I)) {
1314 if (L->getHeader()==I && L->getParentLoop()==0)
1315 printLoop(L);
1316 } else {
1317 printBasicBlock(I);
1318 }
1319 }
1320}
1321
1322
1323void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1324 const Value *left = 0, *right = 0;
1325 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1326 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1327 // Print instruction
1328 switch (CE->getOpcode()) {
1329 case Instruction::Trunc:
1330 case Instruction::ZExt:
1331 case Instruction::SExt:
1332 case Instruction::FPTrunc:
1333 case Instruction::FPExt:
1334 case Instruction::UIToFP:
1335 case Instruction::SIToFP:
1336 case Instruction::FPToUI:
1337 case Instruction::FPToSI:
1338 case Instruction::PtrToInt:
1339 case Instruction::IntToPtr:
1340 case Instruction::BitCast:
1341 printCastInstruction(CE->getOpcode(),left,CE->getType());
1342 break;
1343 case Instruction::GetElementPtr:
1344 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1345 break;
1346 case Instruction::ICmp:
1347 printICmpInstruction(CE->getPredicate(),left,right);
1348 break;
1349 case Instruction::FCmp:
1350 printFCmpInstruction(CE->getPredicate(),left,right);
1351 break;
1352 case Instruction::Select:
1353 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1354 break;
1355 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001356 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001357 printBinaryInstruction("add",left,right);
1358 break;
1359 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001360 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001361 printBinaryInstruction("sub",left,right);
1362 break;
1363 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001364 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001365 printBinaryInstruction("mul",left,right);
1366 break;
1367 case Instruction::UDiv:
1368 printBinaryInstruction("div.un",left,right);
1369 break;
1370 case Instruction::SDiv:
1371 case Instruction::FDiv:
1372 printBinaryInstruction("div",left,right);
1373 break;
1374 case Instruction::URem:
1375 printBinaryInstruction("rem.un",left,right);
1376 break;
1377 case Instruction::SRem:
1378 case Instruction::FRem:
1379 printBinaryInstruction("rem",left,right);
1380 break;
1381 case Instruction::And:
1382 printBinaryInstruction("and",left,right);
1383 break;
1384 case Instruction::Or:
1385 printBinaryInstruction("or",left,right);
1386 break;
1387 case Instruction::Xor:
1388 printBinaryInstruction("xor",left,right);
1389 break;
1390 case Instruction::Shl:
1391 printBinaryInstruction("shl",left,right);
1392 break;
1393 case Instruction::LShr:
1394 printBinaryInstruction("shr.un",left,right);
1395 break;
1396 case Instruction::AShr:
1397 printBinaryInstruction("shr",left,right);
1398 break;
1399 default:
1400 cerr << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001401 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001402 }
1403}
1404
1405
1406void MSILWriter::printStaticInitializerList() {
1407 // List of global variables with uninitialized fields.
1408 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1409 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1410 ++VarI) {
1411 const std::vector<StaticInitializer>& InitList = VarI->second;
1412 if (InitList.empty()) continue;
1413 // For each uninitialized field.
1414 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1415 E = InitList.end(); I!=E; ++I) {
1416 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001417 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1418 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001419 // Load variable address
1420 printValueLoad(VarI->first);
1421 // Add offset
1422 if (I->offset!=0) {
1423 printPtrLoad(I->offset);
1424 printSimpleInstruction("add");
1425 }
1426 // Load value
1427 printConstantExpr(CE);
1428 // Save result at offset
1429 std::string postfix = getTypePostfix(CE->getType(),true);
1430 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1431 postfix = "stind."+postfix;
1432 printSimpleInstruction(postfix.c_str());
1433 } else {
1434 cerr << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001435 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001436 }
1437 }
1438 }
1439}
1440
1441
1442void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001443 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001444 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001445 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001446 if (F.isVarArg()) Out << "vararg ";
1447 Out << getTypeName(F.getReturnType(),isSigned) <<
1448 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1449 // Arguments
1450 Out << "\t(";
1451 unsigned ArgIdx = 1;
1452 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1453 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001454 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001455 if (I!=F.arg_begin()) Out << ", ";
1456 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1457 }
1458 Out << ") cil managed\n";
1459 // Body
1460 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001461 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001462 printFunctionBody(F);
1463 Out << "}\n";
1464}
1465
1466
1467void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1468 std::string Name;
1469 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001470 for (std::set<const Type*>::const_iterator
1471 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1472 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001473 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1474 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001475 // Type with no need to declare.
1476 else continue;
1477 // Print not duplicated type
1478 if (Printed.insert(Ty).second) {
1479 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001480 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001481 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001482 }
1483 }
1484}
1485
1486
1487unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1488 unsigned int N = Ty->getPrimitiveSizeInBits();
1489 assert(N!=0 && "Invalid type in getBitWidth()");
1490 switch (N) {
1491 case 1:
1492 case 8:
1493 case 16:
1494 case 32:
1495 case 64:
1496 return N;
1497 default:
1498 cerr << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001499 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001500 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001501 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001502}
1503
1504
1505void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1506 uint64_t TySize = 0;
1507 const Type* Ty = C->getType();
1508 // Print zero initialized constant.
1509 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001510 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001511 Offset += TySize;
1512 Out << "int8 (0) [" << TySize << "]";
1513 return;
1514 }
1515 // Print constant initializer
1516 switch (Ty->getTypeID()) {
1517 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001518 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001519 const ConstantInt* Int = cast<ConstantInt>(C);
1520 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1521 break;
1522 }
1523 case Type::FloatTyID:
1524 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001525 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001526 const ConstantFP* FP = cast<ConstantFP>(C);
1527 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001528 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001529 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001530 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001531 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001532 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001533 break;
1534 }
1535 case Type::ArrayTyID:
1536 case Type::VectorTyID:
1537 case Type::StructTyID:
1538 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1539 if (I!=0) Out << ",\n";
1540 printStaticConstant(C->getOperand(I),Offset);
1541 }
1542 break;
1543 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001544 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001545 // Initialize with global variable address
1546 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1547 std::string name = getValueName(G);
1548 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1549 } else {
1550 // Dynamic initialization
1551 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1552 InitListPtr->push_back(StaticInitializer(C,Offset));
1553 // Null pointer initialization
1554 if (TySize==4) Out << "int32 (0)";
1555 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001556 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001557 }
1558 break;
1559 default:
1560 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001561 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001562 }
1563 // Increase offset.
1564 Offset += TySize;
1565}
1566
1567
1568void MSILWriter::printStaticInitializer(const Constant* C,
1569 const std::string& Name) {
1570 switch (C->getType()->getTypeID()) {
1571 case Type::IntegerTyID:
1572 case Type::FloatTyID:
1573 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001574 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001575 break;
1576 case Type::ArrayTyID:
1577 case Type::VectorTyID:
1578 case Type::StructTyID:
1579 case Type::PointerTyID:
1580 Out << getTypeName(C->getType());
1581 break;
1582 default:
1583 cerr << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001584 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001585 }
1586 // Print initializer
1587 std::string label = Name;
1588 label.insert(label.length()-1,"$data");
1589 Out << Name << " at " << label << '\n';
1590 Out << ".data " << label << " = {\n";
1591 uint64_t offset = 0;
1592 printStaticConstant(C,offset);
1593 Out << "\n}\n\n";
1594}
1595
1596
1597void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1598 const Constant* C = G->getInitializer();
1599 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1600 InitListPtr = 0;
1601 else
1602 InitListPtr = &StaticInitList[G];
1603 printStaticInitializer(C,getValueName(G));
1604}
1605
1606
1607void MSILWriter::printGlobalVariables() {
1608 if (ModulePtr->global_empty()) return;
1609 Module::global_iterator I,E;
1610 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1611 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001612 Out << ".field static " << (I->isDeclaration() ? "public " :
1613 "private ");
1614 if (I->isDeclaration()) {
1615 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1616 } else
1617 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001618 }
1619}
1620
1621
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001622const char* MSILWriter::getLibraryName(const Function* F) {
1623 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1624}
1625
1626
1627const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001628 return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001629}
1630
1631
1632const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1633 unsigned CallingConv) {
1634 // 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}