blob: 226d146a0e38de13953ab6d178d0a7a438f65a28 [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"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000025#include "llvm/Target/TargetRegistry.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000026#include "llvm/Transforms/Scalar.h"
27#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000028#include "llvm/CodeGen/Passes.h"
Nick Lewycky92fbbc72009-07-26 08:16:51 +000029using namespace llvm;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000030
Nick Lewycky92fbbc72009-07-26 08:16:51 +000031namespace llvm {
Anton Korobeynikov099883f2007-03-21 21:38:25 +000032 // TargetMachine for the MSIL
33 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
Daniel Dunbar214e2232009-08-04 04:02:45 +000034 MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
35 : TargetMachine(T) {}
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
Daniel Dunbard1a919e2009-08-03 17:40:25 +000043 virtual const TargetData *getTargetData() const { return 0; }
Anton Korobeynikov099883f2007-03-21 21:38:25 +000044 };
45}
46
Daniel Dunbar0c795d62009-07-25 06:49:55 +000047extern "C" void LLVMInitializeMSILTarget() {
48 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000049 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000050}
Douglas Gregor1555a232009-06-16 20:12:29 +000051
Anton Korobeynikov099883f2007-03-21 21:38:25 +000052bool MSILModule::runOnModule(Module &M) {
53 ModulePtr = &M;
54 TD = &getAnalysis<TargetData>();
55 bool Changed = false;
56 // Find named types.
57 TypeSymbolTable& Table = M.getTypeSymbolTable();
58 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
59 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
60 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
61 Table.remove(I++);
62 else {
63 std::set<const Type *>::iterator T = Types.find(I->second);
64 if (T==Types.end())
65 Table.remove(I++);
66 else {
67 Types.erase(T);
68 ++I;
69 }
70 }
71 }
72 // Find unnamed types.
73 unsigned RenameCounter = 0;
74 for (std::set<const Type *>::const_iterator I = Types.begin(),
75 E = Types.end(); I!=E; ++I)
76 if (const StructType *STy = dyn_cast<StructType>(*I)) {
77 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
78 ++RenameCounter;
79 Changed = true;
80 }
81 // Pointer for FunctionPass.
82 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
83 return Changed;
84}
85
Devang Patel19974732007-05-03 01:11:54 +000086char MSILModule::ID = 0;
87char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000088
89bool MSILWriter::runOnFunction(Function &F) {
90 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000091
92 // Do not codegen any 'available_externally' functions at all, they have
93 // definitions outside the translation unit.
94 if (F.hasAvailableExternallyLinkage())
95 return false;
96
Anton Korobeynikov099883f2007-03-21 21:38:25 +000097 LInfo = &getAnalysis<LoopInfo>();
98 printFunction(F);
99 return false;
100}
101
102
103bool MSILWriter::doInitialization(Module &M) {
104 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000105 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000106 Out << ".assembly extern mscorlib {}\n";
107 Out << ".assembly MSIL {}\n\n";
108 Out << "// External\n";
109 printExternals();
110 Out << "// Declarations\n";
111 printDeclarations(M.getTypeSymbolTable());
112 Out << "// Definitions\n";
113 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000114 Out << "// Startup code\n";
115 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000116 return false;
117}
118
119
120bool MSILWriter::doFinalization(Module &M) {
121 delete Mang;
122 return false;
123}
124
125
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000126void MSILWriter::printModuleStartup() {
127 Out <<
128 ".method static public int32 $MSIL_Startup() {\n"
129 "\t.entrypoint\n"
130 "\t.locals (native int i)\n"
131 "\t.locals (native int argc)\n"
132 "\t.locals (native int ptr)\n"
133 "\t.locals (void* argv)\n"
134 "\t.locals (string[] args)\n"
135 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
136 "\tdup\n"
137 "\tstloc\targs\n"
138 "\tldlen\n"
139 "\tconv.i4\n"
140 "\tdup\n"
141 "\tstloc\targc\n";
142 printPtrLoad(TD->getPointerSize());
143 Out <<
144 "\tmul\n"
145 "\tlocalloc\n"
146 "\tstloc\targv\n"
147 "\tldc.i4.0\n"
148 "\tstloc\ti\n"
149 "L_01:\n"
150 "\tldloc\ti\n"
151 "\tldloc\targc\n"
152 "\tceq\n"
153 "\tbrtrue\tL_02\n"
154 "\tldloc\targs\n"
155 "\tldloc\ti\n"
156 "\tldelem.ref\n"
157 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
158 "StringToHGlobalAnsi(string)\n"
159 "\tstloc\tptr\n"
160 "\tldloc\targv\n"
161 "\tldloc\ti\n";
162 printPtrLoad(TD->getPointerSize());
163 Out <<
164 "\tmul\n"
165 "\tadd\n"
166 "\tldloc\tptr\n"
167 "\tstind.i\n"
168 "\tldloc\ti\n"
169 "\tldc.i4.1\n"
170 "\tadd\n"
171 "\tstloc\ti\n"
172 "\tbr\tL_01\n"
173 "L_02:\n"
174 "\tcall void $MSIL_Init()\n";
175
176 // Call user 'main' function.
177 const Function* F = ModulePtr->getFunction("main");
178 if (!F || F->isDeclaration()) {
179 Out << "\tldc.i4.0\n\tret\n}\n";
180 return;
181 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000182 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000183 std::string Args("");
184 Function::const_arg_iterator Arg1,Arg2;
185
186 switch (F->arg_size()) {
187 case 0:
188 BadSig = false;
189 break;
190 case 1:
191 Arg1 = F->arg_begin();
192 if (Arg1->getType()->isInteger()) {
193 Out << "\tldloc\targc\n";
194 Args = getTypeName(Arg1->getType());
195 BadSig = false;
196 }
197 break;
198 case 2:
199 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
200 if (Arg1->getType()->isInteger() &&
201 Arg2->getType()->getTypeID() == Type::PointerTyID) {
202 Out << "\tldloc\targc\n\tldloc\targv\n";
203 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
204 BadSig = false;
205 }
206 break;
207 default:
208 BadSig = true;
209 }
210
211 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000212 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000213 Out << "\tldc.i4.0\n";
214 } else {
215 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
216 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
217 if (RetVoid)
218 Out << "\tldc.i4.0\n";
219 else
220 Out << "\tconv.i4\n";
221 }
222 Out << "\tret\n}\n";
223}
224
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000225bool MSILWriter::isZeroValue(const Value* V) {
226 if (const Constant *C = dyn_cast<Constant>(V))
227 return C->isNullValue();
228 return false;
229}
230
231
232std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000233 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000234 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000235 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000236 else {
237 unsigned &No = AnonValueNumbers[V];
238 if (No == 0) No = ++NextAnonValueNumber;
239 Name = "tmp" + utostr(No);
240 }
241
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000242 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000243 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000244}
245
246
247std::string MSILWriter::getLabelName(const std::string& Name) {
248 if (Name.find('.')!=std::string::npos) {
249 std::string Tmp(Name);
250 // Replace unaccepable characters in the label name.
251 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
252 if (*I=='.') *I = '@';
253 return Tmp;
254 }
255 return Name;
256}
257
258
259std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000260 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000261 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000262 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000263 else {
264 unsigned &No = AnonValueNumbers[V];
265 if (No == 0) No = ++NextAnonValueNumber;
266 Name = "tmp" + utostr(No);
267 }
268
269 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000270}
271
272
273std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
274 switch (CallingConvID) {
275 case CallingConv::C:
276 case CallingConv::Cold:
277 case CallingConv::Fast:
278 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
279 case CallingConv::X86_FastCall:
280 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
281 case CallingConv::X86_StdCall:
282 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
283 default:
284 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000285 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000286 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000287 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000288}
289
290
291std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
292 std::string Tmp = "";
293 const Type* ElemTy = Ty;
294 assert(Ty->getTypeID()==TyID && "Invalid type passed");
295 // Walk trought array element types.
296 for (;;) {
297 // Multidimensional array.
298 if (ElemTy->getTypeID()==TyID) {
299 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
300 Tmp += utostr(ATy->getNumElements());
301 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
302 Tmp += utostr(VTy->getNumElements());
303 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
304 }
305 // Base element type found.
306 if (ElemTy->getTypeID()!=TyID) break;
307 Tmp += ",";
308 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000309 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000310}
311
312
313std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
314 unsigned NumBits = 0;
315 switch (Ty->getTypeID()) {
316 case Type::VoidTyID:
317 return "void ";
318 case Type::IntegerTyID:
319 NumBits = getBitWidth(Ty);
320 if(NumBits==1)
321 return "bool ";
322 if (!isSigned)
323 return "unsigned int"+utostr(NumBits)+" ";
324 return "int"+utostr(NumBits)+" ";
325 case Type::FloatTyID:
326 return "float32 ";
327 case Type::DoubleTyID:
328 return "float64 ";
329 default:
330 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000331 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000332 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000333 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000334}
335
336
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000337std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
338 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000339 if (Ty->isPrimitiveType() || Ty->isInteger())
340 return getPrimitiveTypeName(Ty,isSigned);
341 // FIXME: "OpaqueType" support
342 switch (Ty->getTypeID()) {
343 case Type::PointerTyID:
344 return "void* ";
345 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000346 if (isNested)
347 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000348 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
349 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000350 if (isNested)
351 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000352 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
353 case Type::VectorTyID:
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 default:
358 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000359 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000360 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000361 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000362}
363
364
365MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
366 // Function argument
367 if (isa<Argument>(V))
368 return ArgumentVT;
369 // Function
370 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000371 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000372 // Variable
373 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000374 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000375 // Constant
376 else if (isa<Constant>(V))
377 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
378 // Local variable
379 return LocalVT;
380}
381
382
383std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
384 bool isSigned) {
385 unsigned NumBits = 0;
386 switch (Ty->getTypeID()) {
387 // Integer constant, expanding for stack operations.
388 case Type::IntegerTyID:
389 NumBits = getBitWidth(Ty);
390 // Expand integer value to "int32" or "int64".
391 if (Expand) return (NumBits<=32 ? "i4" : "i8");
392 if (NumBits==1) return "i1";
393 return (isSigned ? "i" : "u")+utostr(NumBits/8);
394 // Float constant.
395 case Type::FloatTyID:
396 return "r4";
397 case Type::DoubleTyID:
398 return "r8";
399 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000400 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000401 default:
402 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000403 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000404 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000405 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000406}
407
408
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000409void MSILWriter::printConvToPtr() {
410 switch (ModulePtr->getPointerSize()) {
411 case Module::Pointer32:
412 printSimpleInstruction("conv.u4");
413 break;
414 case Module::Pointer64:
415 printSimpleInstruction("conv.u8");
416 break;
417 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000418 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000419 }
420}
421
422
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000423void MSILWriter::printPtrLoad(uint64_t N) {
424 switch (ModulePtr->getPointerSize()) {
425 case Module::Pointer32:
426 printSimpleInstruction("ldc.i4",utostr(N).c_str());
427 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000428 if (!isUInt32(N)) {
429 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000430 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000431 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000432 break;
433 case Module::Pointer64:
434 printSimpleInstruction("ldc.i8",utostr(N).c_str());
435 break;
436 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000437 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000438 }
439}
440
441
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000442void MSILWriter::printValuePtrLoad(const Value* V) {
443 printValueLoad(V);
444 printConvToPtr();
445}
446
447
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000448void MSILWriter::printConstLoad(const Constant* C) {
449 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
450 // Integer constant
451 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
452 if (CInt->isMinValue(true))
453 Out << CInt->getSExtValue();
454 else
455 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000456 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000457 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000458 uint64_t X;
459 unsigned Size;
460 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000461 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000462 Size = 4;
463 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000464 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000465 Size = 8;
466 }
467 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
468 } else if (isa<UndefValue>(C)) {
469 // Undefined constant value = NULL.
470 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000471 } else {
472 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000473 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000474 }
475 Out << '\n';
476}
477
478
479void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000480 MSILWriter::ValueType Location = getValueLocation(V);
481 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000482 // Global variable or function address.
483 case GlobalVT:
484 case InternalVT:
485 if (const Function* F = dyn_cast<Function>(V)) {
486 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
487 printSimpleInstruction("ldftn",
488 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
489 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000490 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000491 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000492 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
493 Tmp = "void* "+getValueName(V);
494 printSimpleInstruction("ldsfld",Tmp.c_str());
495 } else {
496 Tmp = getTypeName(ElemTy)+getValueName(V);
497 printSimpleInstruction("ldsflda",Tmp.c_str());
498 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000499 }
500 break;
501 // Function argument.
502 case ArgumentVT:
503 printSimpleInstruction("ldarg",getValueName(V).c_str());
504 break;
505 // Local function variable.
506 case LocalVT:
507 printSimpleInstruction("ldloc",getValueName(V).c_str());
508 break;
509 // Constant value.
510 case ConstVT:
511 if (isa<ConstantPointerNull>(V))
512 printPtrLoad(0);
513 else
514 printConstLoad(cast<Constant>(V));
515 break;
516 // Constant expression.
517 case ConstExprVT:
518 printConstantExpr(cast<ConstantExpr>(V));
519 break;
520 default:
521 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000522 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000523 }
524}
525
526
527void MSILWriter::printValueSave(const Value* V) {
528 switch (getValueLocation(V)) {
529 case ArgumentVT:
530 printSimpleInstruction("starg",getValueName(V).c_str());
531 break;
532 case LocalVT:
533 printSimpleInstruction("stloc",getValueName(V).c_str());
534 break;
535 default:
536 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000537 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000538 }
539}
540
541
542void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
543 const Value* Right) {
544 printValueLoad(Left);
545 printValueLoad(Right);
546 Out << '\t' << Name << '\n';
547}
548
549
550void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
551 if(Operand)
552 Out << '\t' << Inst << '\t' << Operand << '\n';
553 else
554 Out << '\t' << Inst << '\n';
555}
556
557
558void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
559 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
560 isa<PHINode>(I); ++I) {
561 const PHINode* Phi = cast<PHINode>(I);
562 const Value* Val = Phi->getIncomingValueForBlock(Src);
563 if (isa<UndefValue>(Val)) continue;
564 printValueLoad(Val);
565 printValueSave(Phi);
566 }
567}
568
569
570void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
571 const BasicBlock* TrueBB,
572 const BasicBlock* FalseBB) {
573 if (TrueBB==FalseBB) {
574 // "TrueBB" and "FalseBB" destination equals
575 printPHICopy(CurrBB,TrueBB);
576 printSimpleInstruction("pop");
577 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
578 } else if (FalseBB==NULL) {
579 // If "FalseBB" not used the jump have condition
580 printPHICopy(CurrBB,TrueBB);
581 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
582 } else if (TrueBB==NULL) {
583 // If "TrueBB" not used the jump is unconditional
584 printPHICopy(CurrBB,FalseBB);
585 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
586 } else {
587 // Copy PHI instructions for each block
588 std::string TmpLabel;
589 // Print PHI instructions for "TrueBB"
590 if (isa<PHINode>(TrueBB->begin())) {
591 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
592 printSimpleInstruction("brtrue",TmpLabel.c_str());
593 } else {
594 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
595 }
596 // Print PHI instructions for "FalseBB"
597 if (isa<PHINode>(FalseBB->begin())) {
598 printPHICopy(CurrBB,FalseBB);
599 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
600 } else {
601 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
602 }
603 if (isa<PHINode>(TrueBB->begin())) {
604 // Handle "TrueBB" PHI Copy
605 Out << TmpLabel << ":\n";
606 printPHICopy(CurrBB,TrueBB);
607 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
608 }
609 }
610}
611
612
613void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
614 if (Inst->isUnconditional()) {
615 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
616 } else {
617 printValueLoad(Inst->getCondition());
618 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
619 Inst->getSuccessor(1));
620 }
621}
622
623
624void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
625 const Value* VFalse) {
626 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
627 printValueLoad(VTrue);
628 printValueLoad(Cond);
629 printSimpleInstruction("brtrue",TmpLabel.c_str());
630 printSimpleInstruction("pop");
631 printValueLoad(VFalse);
632 Out << TmpLabel << ":\n";
633}
634
635
636void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000637 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000638 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000639 if (const PointerType* P = dyn_cast<PointerType>(Ty))
640 Ty = P->getElementType();
641 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000642 printSimpleInstruction(Tmp.c_str());
643}
644
645
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000646void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000647 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000648 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000649 printIndirectSave(Val->getType());
650}
651
652
653void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000654 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000655 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000656 if (*postfix.begin()=='u') *postfix.begin() = 'i';
657 postfix = "stind."+postfix;
658 printSimpleInstruction(postfix.c_str());
659}
660
661
662void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000663 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000664 std::string Tmp("");
665 printValueLoad(V);
666 switch (Op) {
667 // Signed
668 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000669 // If sign extending int, convert first from unsigned to signed
670 // with the same bit size - because otherwise we will loose the sign.
671 if (SrcTy) {
672 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
673 printSimpleInstruction(Tmp.c_str());
674 }
Bill Wendling5f544502009-07-14 18:30:04 +0000675 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000676 case Instruction::SIToFP:
677 case Instruction::FPToSI:
678 Tmp = "conv."+getTypePostfix(Ty,false,true);
679 printSimpleInstruction(Tmp.c_str());
680 break;
681 // Unsigned
682 case Instruction::FPTrunc:
683 case Instruction::FPExt:
684 case Instruction::UIToFP:
685 case Instruction::Trunc:
686 case Instruction::ZExt:
687 case Instruction::FPToUI:
688 case Instruction::PtrToInt:
689 case Instruction::IntToPtr:
690 Tmp = "conv."+getTypePostfix(Ty,false);
691 printSimpleInstruction(Tmp.c_str());
692 break;
693 // Do nothing
694 case Instruction::BitCast:
695 // FIXME: meaning that ld*/st* instruction do not change data format.
696 break;
697 default:
698 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000699 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000700 }
701}
702
703
704void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
705 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000706 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000707 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000708 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000709 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000710 for (; I!=E; ++I){
711 Size = 0;
712 const Value* IndexValue = I.getOperand();
713 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
714 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
715 // Offset is the sum of all previous structure fields.
716 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000717 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000718 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000719 printSimpleInstruction("add");
720 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000721 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000722 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000723 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000724 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000725 }
726 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000727 if (!isZeroValue(IndexValue)) {
728 // Constant optimization.
729 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
730 if (C->getValue().isNegative()) {
731 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
732 printSimpleInstruction("sub");
733 continue;
734 } else
735 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000736 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000737 printPtrLoad(Size);
738 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000739 printSimpleInstruction("mul");
740 }
741 printSimpleInstruction("add");
742 }
743 }
744}
745
746
747std::string MSILWriter::getCallSignature(const FunctionType* Ty,
748 const Instruction* Inst,
749 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000750 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000751 if (Ty->isVarArg()) Tmp += "vararg ";
752 // Name and return type.
753 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
754 // Function argument type list.
755 unsigned NumParams = Ty->getNumParams();
756 for (unsigned I = 0; I!=NumParams; ++I) {
757 if (I!=0) Tmp += ",";
758 Tmp += getTypeName(Ty->getParamType(I));
759 }
760 // CLR needs to know the exact amount of parameters received by vararg
761 // function, because caller cleans the stack.
762 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000763 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000764 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
765 // Print variable argument types.
766 unsigned NumOperands = Inst->getNumOperands()-Org;
767 if (NumParams<NumOperands) {
768 if (NumParams!=0) Tmp += ", ";
769 Tmp += "... , ";
770 for (unsigned J = NumParams; J!=NumOperands; ++J) {
771 if (J!=NumParams) Tmp += ", ";
772 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
773 }
774 }
775 }
776 return Tmp+")";
777}
778
779
780void MSILWriter::printFunctionCall(const Value* FnVal,
781 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000782 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000783 std::string Name = "";
784 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
785 Name = getConvModopt(Call->getCallingConv());
786 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
787 Name = getConvModopt(Invoke->getCallingConv());
788 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000789 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000790 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000791 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000792 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000793 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000794 Name += getValueName(F);
795 printSimpleInstruction("call",
796 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
797 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000798 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000799 const PointerType* PTy = cast<PointerType>(FnVal->getType());
800 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000801 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000802 printValueLoad(FnVal);
803 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
804 }
805}
806
807
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000808void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
809 std::string Name;
810 switch (Inst->getIntrinsicID()) {
811 case Intrinsic::vastart:
812 Name = getValueName(Inst->getOperand(1));
813 Name.insert(Name.length()-1,"$valist");
814 // Obtain the argument handle.
815 printSimpleInstruction("ldloca",Name.c_str());
816 printSimpleInstruction("arglist");
817 printSimpleInstruction("call",
818 "instance void [mscorlib]System.ArgIterator::.ctor"
819 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
820 // Save as pointer type "void*"
821 printValueLoad(Inst->getOperand(1));
822 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000823 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000824 break;
825 case Intrinsic::vaend:
826 // Close argument list handle.
827 printIndirectLoad(Inst->getOperand(1));
828 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
829 break;
830 case Intrinsic::vacopy:
831 // Copy "ArgIterator" valuetype.
832 printIndirectLoad(Inst->getOperand(1));
833 printIndirectLoad(Inst->getOperand(2));
834 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
835 break;
836 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000837 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000838 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000839 }
840}
841
842
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000843void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000844 if (isa<IntrinsicInst>(Inst)) {
845 // Handle intrinsic function.
846 printIntrinsicCall(cast<IntrinsicInst>(Inst));
847 } else {
848 // Load arguments to stack and call function.
849 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
850 printValueLoad(Inst->getOperand(I));
851 printFunctionCall(Inst->getOperand(0),Inst);
852 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000853}
854
855
856void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
857 const Value* Right) {
858 switch (Predicate) {
859 case ICmpInst::ICMP_EQ:
860 printBinaryInstruction("ceq",Left,Right);
861 break;
862 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000863 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000864 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000865 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000866 printSimpleInstruction("not");
867 break;
868 case ICmpInst::ICMP_ULE:
869 case ICmpInst::ICMP_SLE:
870 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
871 printBinaryInstruction("ceq",Left,Right);
872 if (Predicate==ICmpInst::ICMP_ULE)
873 printBinaryInstruction("clt.un",Left,Right);
874 else
875 printBinaryInstruction("clt",Left,Right);
876 printSimpleInstruction("or");
877 break;
878 case ICmpInst::ICMP_UGE:
879 case ICmpInst::ICMP_SGE:
880 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
881 printBinaryInstruction("ceq",Left,Right);
882 if (Predicate==ICmpInst::ICMP_UGE)
883 printBinaryInstruction("cgt.un",Left,Right);
884 else
885 printBinaryInstruction("cgt",Left,Right);
886 printSimpleInstruction("or");
887 break;
888 case ICmpInst::ICMP_ULT:
889 printBinaryInstruction("clt.un",Left,Right);
890 break;
891 case ICmpInst::ICMP_SLT:
892 printBinaryInstruction("clt",Left,Right);
893 break;
894 case ICmpInst::ICMP_UGT:
895 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000896 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000897 case ICmpInst::ICMP_SGT:
898 printBinaryInstruction("cgt",Left,Right);
899 break;
900 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000901 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000902 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000903 }
904}
905
906
907void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
908 const Value* Right) {
909 // FIXME: Correct comparison
910 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
911 switch (Predicate) {
912 case FCmpInst::FCMP_UGT:
913 // X > Y || llvm_fcmp_uno(X, Y)
914 printBinaryInstruction("cgt",Left,Right);
915 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
916 printSimpleInstruction("or");
917 break;
918 case FCmpInst::FCMP_OGT:
919 // X > Y
920 printBinaryInstruction("cgt",Left,Right);
921 break;
922 case FCmpInst::FCMP_UGE:
923 // X >= Y || llvm_fcmp_uno(X, Y)
924 printBinaryInstruction("ceq",Left,Right);
925 printBinaryInstruction("cgt",Left,Right);
926 printSimpleInstruction("or");
927 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
928 printSimpleInstruction("or");
929 break;
930 case FCmpInst::FCMP_OGE:
931 // X >= Y
932 printBinaryInstruction("ceq",Left,Right);
933 printBinaryInstruction("cgt",Left,Right);
934 printSimpleInstruction("or");
935 break;
936 case FCmpInst::FCMP_ULT:
937 // X < Y || llvm_fcmp_uno(X, Y)
938 printBinaryInstruction("clt",Left,Right);
939 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
940 printSimpleInstruction("or");
941 break;
942 case FCmpInst::FCMP_OLT:
943 // X < Y
944 printBinaryInstruction("clt",Left,Right);
945 break;
946 case FCmpInst::FCMP_ULE:
947 // X <= Y || llvm_fcmp_uno(X, Y)
948 printBinaryInstruction("ceq",Left,Right);
949 printBinaryInstruction("clt",Left,Right);
950 printSimpleInstruction("or");
951 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
952 printSimpleInstruction("or");
953 break;
954 case FCmpInst::FCMP_OLE:
955 // X <= Y
956 printBinaryInstruction("ceq",Left,Right);
957 printBinaryInstruction("clt",Left,Right);
958 printSimpleInstruction("or");
959 break;
960 case FCmpInst::FCMP_UEQ:
961 // X == Y || llvm_fcmp_uno(X, Y)
962 printBinaryInstruction("ceq",Left,Right);
963 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
964 printSimpleInstruction("or");
965 break;
966 case FCmpInst::FCMP_OEQ:
967 // X == Y
968 printBinaryInstruction("ceq",Left,Right);
969 break;
970 case FCmpInst::FCMP_UNE:
971 // X != Y
972 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000973 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000974 printSimpleInstruction("not");
975 break;
976 case FCmpInst::FCMP_ONE:
977 // X != Y && llvm_fcmp_ord(X, Y)
978 printBinaryInstruction("ceq",Left,Right);
979 printSimpleInstruction("not");
980 break;
981 case FCmpInst::FCMP_ORD:
982 // return X == X && Y == Y
983 printBinaryInstruction("ceq",Left,Left);
984 printBinaryInstruction("ceq",Right,Right);
985 printSimpleInstruction("or");
986 break;
987 case FCmpInst::FCMP_UNO:
988 // X != X || Y != Y
989 printBinaryInstruction("ceq",Left,Left);
990 printSimpleInstruction("not");
991 printBinaryInstruction("ceq",Right,Right);
992 printSimpleInstruction("not");
993 printSimpleInstruction("or");
994 break;
995 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000996 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000997 }
998}
999
1000
1001void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1002 std::string Label = "leave$normal_"+utostr(getUniqID());
1003 Out << ".try {\n";
1004 // Load arguments
1005 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1006 printValueLoad(Inst->getOperand(I));
1007 // Print call instruction
1008 printFunctionCall(Inst->getOperand(0),Inst);
1009 // Save function result and leave "try" block
1010 printValueSave(Inst);
1011 printSimpleInstruction("leave",Label.c_str());
1012 Out << "}\n";
1013 Out << "catch [mscorlib]System.Exception {\n";
1014 // Redirect to unwind block
1015 printSimpleInstruction("pop");
1016 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1017 Out << "}\n" << Label << ":\n";
1018 // Redirect to continue block
1019 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1020}
1021
1022
1023void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1024 // FIXME: Emulate with IL "switch" instruction
1025 // Emulate = if () else if () else if () else ...
1026 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1027 printValueLoad(Inst->getCondition());
1028 printValueLoad(Inst->getCaseValue(I));
1029 printSimpleInstruction("ceq");
1030 // Condition jump to successor block
1031 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1032 }
1033 // Jump to default block
1034 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1035}
1036
1037
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001038void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1039 printIndirectLoad(Inst->getOperand(0));
1040 printSimpleInstruction("call",
1041 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1042 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001043 std::string Name =
1044 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001045 printSimpleInstruction(Name.c_str());
1046}
1047
1048
1049void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001050 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001051 // Constant optimization.
1052 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1053 printPtrLoad(CInt->getZExtValue()*Size);
1054 } else {
1055 printPtrLoad(Size);
1056 printValueLoad(Inst->getOperand(0));
1057 printSimpleInstruction("mul");
1058 }
1059 printSimpleInstruction("localloc");
1060}
1061
1062
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001063void MSILWriter::printInstruction(const Instruction* Inst) {
1064 const Value *Left = 0, *Right = 0;
1065 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1066 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1067 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001068 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001069 switch (Inst->getOpcode()) {
1070 // Terminator
1071 case Instruction::Ret:
1072 if (Inst->getNumOperands()) {
1073 printValueLoad(Left);
1074 printSimpleInstruction("ret");
1075 } else
1076 printSimpleInstruction("ret");
1077 break;
1078 case Instruction::Br:
1079 printBranchInstruction(cast<BranchInst>(Inst));
1080 break;
1081 // Binary
1082 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001083 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001084 printBinaryInstruction("add",Left,Right);
1085 break;
1086 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001087 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001088 printBinaryInstruction("sub",Left,Right);
1089 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001090 case Instruction::Mul:
1091 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001092 printBinaryInstruction("mul",Left,Right);
1093 break;
1094 case Instruction::UDiv:
1095 printBinaryInstruction("div.un",Left,Right);
1096 break;
1097 case Instruction::SDiv:
1098 case Instruction::FDiv:
1099 printBinaryInstruction("div",Left,Right);
1100 break;
1101 case Instruction::URem:
1102 printBinaryInstruction("rem.un",Left,Right);
1103 break;
1104 case Instruction::SRem:
1105 case Instruction::FRem:
1106 printBinaryInstruction("rem",Left,Right);
1107 break;
1108 // Binary Condition
1109 case Instruction::ICmp:
1110 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1111 break;
1112 case Instruction::FCmp:
1113 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1114 break;
1115 // Bitwise Binary
1116 case Instruction::And:
1117 printBinaryInstruction("and",Left,Right);
1118 break;
1119 case Instruction::Or:
1120 printBinaryInstruction("or",Left,Right);
1121 break;
1122 case Instruction::Xor:
1123 printBinaryInstruction("xor",Left,Right);
1124 break;
1125 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001126 printValueLoad(Left);
1127 printValueLoad(Right);
1128 printSimpleInstruction("conv.i4");
1129 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001130 break;
1131 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001132 printValueLoad(Left);
1133 printValueLoad(Right);
1134 printSimpleInstruction("conv.i4");
1135 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001136 break;
1137 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001138 printValueLoad(Left);
1139 printValueLoad(Right);
1140 printSimpleInstruction("conv.i4");
1141 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001142 break;
1143 case Instruction::Select:
1144 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1145 break;
1146 case Instruction::Load:
1147 printIndirectLoad(Inst->getOperand(0));
1148 break;
1149 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001150 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001151 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001152 case Instruction::SExt:
1153 printCastInstruction(Inst->getOpcode(),Left,
1154 cast<CastInst>(Inst)->getDestTy(),
1155 cast<CastInst>(Inst)->getSrcTy());
1156 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001157 case Instruction::Trunc:
1158 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001159 case Instruction::FPTrunc:
1160 case Instruction::FPExt:
1161 case Instruction::UIToFP:
1162 case Instruction::SIToFP:
1163 case Instruction::FPToUI:
1164 case Instruction::FPToSI:
1165 case Instruction::PtrToInt:
1166 case Instruction::IntToPtr:
1167 case Instruction::BitCast:
1168 printCastInstruction(Inst->getOpcode(),Left,
1169 cast<CastInst>(Inst)->getDestTy());
1170 break;
1171 case Instruction::GetElementPtr:
1172 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1173 gep_type_end(Inst));
1174 break;
1175 case Instruction::Call:
1176 printCallInstruction(cast<CallInst>(Inst));
1177 break;
1178 case Instruction::Invoke:
1179 printInvokeInstruction(cast<InvokeInst>(Inst));
1180 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001181 case Instruction::Unwind:
1182 printSimpleInstruction("newobj",
1183 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001184 printSimpleInstruction("throw");
1185 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001186 case Instruction::Switch:
1187 printSwitchInstruction(cast<SwitchInst>(Inst));
1188 break;
1189 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001190 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001191 break;
1192 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001193 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001194 break;
1195 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001196 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001197 break;
1198 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001199 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1200 printSimpleInstruction("newobj",
1201 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001202 printSimpleInstruction("throw");
1203 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001204 case Instruction::VAArg:
1205 printVAArgInstruction(cast<VAArgInst>(Inst));
1206 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001207 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001208 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001209 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001210 }
1211}
1212
1213
1214void MSILWriter::printLoop(const Loop* L) {
1215 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1216 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1217 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1218 BasicBlock* BB = blocks[I];
1219 Loop* BBLoop = LInfo->getLoopFor(BB);
1220 if (BBLoop == L)
1221 printBasicBlock(BB);
1222 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1223 printLoop(BBLoop);
1224 }
1225 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1226}
1227
1228
1229void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1230 Out << getLabelName(BB) << ":\n";
1231 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1232 const Instruction* Inst = I;
1233 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001234 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001235 // Do not handle PHI instruction in current block
1236 if (Inst->getOpcode()==Instruction::PHI) continue;
1237 // Print instruction
1238 printInstruction(Inst);
1239 // Save result
1240 if (Inst->getType()!=Type::VoidTy) {
1241 // Do not save value after invoke, it done in "try" block
1242 if (Inst->getOpcode()==Instruction::Invoke) continue;
1243 printValueSave(Inst);
1244 }
1245 }
1246}
1247
1248
1249void MSILWriter::printLocalVariables(const Function& F) {
1250 std::string Name;
1251 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001252 std::set<const Value*> Printed;
1253 const Value* VaList = NULL;
1254 unsigned StackDepth = 8;
1255 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001256 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001257 if (I->getOpcode()==Instruction::Call ||
1258 I->getOpcode()==Instruction::Invoke) {
1259 // Test stack depth.
1260 if (StackDepth<I->getNumOperands())
1261 StackDepth = I->getNumOperands();
1262 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001263 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1264 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001265 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001266 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001267 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001268 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001269 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001270 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001271 Ty = I->getType();
1272 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001273 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1274 }
1275 // Test on 'va_list' variable
1276 bool isVaList = false;
1277 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1278 // "va_list" as "va_arg" instruction operand.
1279 isVaList = true;
1280 VaList = VaInst->getOperand(0);
1281 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1282 // "va_list" as intrinsic function operand.
1283 switch (Inst->getIntrinsicID()) {
1284 case Intrinsic::vastart:
1285 case Intrinsic::vaend:
1286 case Intrinsic::vacopy:
1287 isVaList = true;
1288 VaList = Inst->getOperand(1);
1289 break;
1290 default:
1291 isVaList = false;
1292 }
1293 }
1294 // Print "va_list" variable.
1295 if (isVaList && Printed.insert(VaList).second) {
1296 Name = getValueName(VaList);
1297 Name.insert(Name.length()-1,"$valist");
1298 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1299 << Name << ")\n";
1300 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001301 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001302 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001303}
1304
1305
1306void MSILWriter::printFunctionBody(const Function& F) {
1307 // Print body
1308 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1309 if (Loop *L = LInfo->getLoopFor(I)) {
1310 if (L->getHeader()==I && L->getParentLoop()==0)
1311 printLoop(L);
1312 } else {
1313 printBasicBlock(I);
1314 }
1315 }
1316}
1317
1318
1319void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1320 const Value *left = 0, *right = 0;
1321 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1322 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1323 // Print instruction
1324 switch (CE->getOpcode()) {
1325 case Instruction::Trunc:
1326 case Instruction::ZExt:
1327 case Instruction::SExt:
1328 case Instruction::FPTrunc:
1329 case Instruction::FPExt:
1330 case Instruction::UIToFP:
1331 case Instruction::SIToFP:
1332 case Instruction::FPToUI:
1333 case Instruction::FPToSI:
1334 case Instruction::PtrToInt:
1335 case Instruction::IntToPtr:
1336 case Instruction::BitCast:
1337 printCastInstruction(CE->getOpcode(),left,CE->getType());
1338 break;
1339 case Instruction::GetElementPtr:
1340 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1341 break;
1342 case Instruction::ICmp:
1343 printICmpInstruction(CE->getPredicate(),left,right);
1344 break;
1345 case Instruction::FCmp:
1346 printFCmpInstruction(CE->getPredicate(),left,right);
1347 break;
1348 case Instruction::Select:
1349 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1350 break;
1351 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001352 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001353 printBinaryInstruction("add",left,right);
1354 break;
1355 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001356 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001357 printBinaryInstruction("sub",left,right);
1358 break;
1359 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001360 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001361 printBinaryInstruction("mul",left,right);
1362 break;
1363 case Instruction::UDiv:
1364 printBinaryInstruction("div.un",left,right);
1365 break;
1366 case Instruction::SDiv:
1367 case Instruction::FDiv:
1368 printBinaryInstruction("div",left,right);
1369 break;
1370 case Instruction::URem:
1371 printBinaryInstruction("rem.un",left,right);
1372 break;
1373 case Instruction::SRem:
1374 case Instruction::FRem:
1375 printBinaryInstruction("rem",left,right);
1376 break;
1377 case Instruction::And:
1378 printBinaryInstruction("and",left,right);
1379 break;
1380 case Instruction::Or:
1381 printBinaryInstruction("or",left,right);
1382 break;
1383 case Instruction::Xor:
1384 printBinaryInstruction("xor",left,right);
1385 break;
1386 case Instruction::Shl:
1387 printBinaryInstruction("shl",left,right);
1388 break;
1389 case Instruction::LShr:
1390 printBinaryInstruction("shr.un",left,right);
1391 break;
1392 case Instruction::AShr:
1393 printBinaryInstruction("shr",left,right);
1394 break;
1395 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001396 errs() << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001397 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001398 }
1399}
1400
1401
1402void MSILWriter::printStaticInitializerList() {
1403 // List of global variables with uninitialized fields.
1404 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1405 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1406 ++VarI) {
1407 const std::vector<StaticInitializer>& InitList = VarI->second;
1408 if (InitList.empty()) continue;
1409 // For each uninitialized field.
1410 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1411 E = InitList.end(); I!=E; ++I) {
1412 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001413 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1414 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001415 // Load variable address
1416 printValueLoad(VarI->first);
1417 // Add offset
1418 if (I->offset!=0) {
1419 printPtrLoad(I->offset);
1420 printSimpleInstruction("add");
1421 }
1422 // Load value
1423 printConstantExpr(CE);
1424 // Save result at offset
1425 std::string postfix = getTypePostfix(CE->getType(),true);
1426 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1427 postfix = "stind."+postfix;
1428 printSimpleInstruction(postfix.c_str());
1429 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001430 errs() << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001431 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001432 }
1433 }
1434 }
1435}
1436
1437
1438void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001439 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001440 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001441 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001442 if (F.isVarArg()) Out << "vararg ";
1443 Out << getTypeName(F.getReturnType(),isSigned) <<
1444 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1445 // Arguments
1446 Out << "\t(";
1447 unsigned ArgIdx = 1;
1448 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1449 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001450 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001451 if (I!=F.arg_begin()) Out << ", ";
1452 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1453 }
1454 Out << ") cil managed\n";
1455 // Body
1456 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001457 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001458 printFunctionBody(F);
1459 Out << "}\n";
1460}
1461
1462
1463void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1464 std::string Name;
1465 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001466 for (std::set<const Type*>::const_iterator
1467 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1468 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001469 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1470 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001471 // Type with no need to declare.
1472 else continue;
1473 // Print not duplicated type
1474 if (Printed.insert(Ty).second) {
1475 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001476 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001477 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001478 }
1479 }
1480}
1481
1482
1483unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1484 unsigned int N = Ty->getPrimitiveSizeInBits();
1485 assert(N!=0 && "Invalid type in getBitWidth()");
1486 switch (N) {
1487 case 1:
1488 case 8:
1489 case 16:
1490 case 32:
1491 case 64:
1492 return N;
1493 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001494 errs() << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001495 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001496 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001497 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001498}
1499
1500
1501void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1502 uint64_t TySize = 0;
1503 const Type* Ty = C->getType();
1504 // Print zero initialized constant.
1505 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001506 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001507 Offset += TySize;
1508 Out << "int8 (0) [" << TySize << "]";
1509 return;
1510 }
1511 // Print constant initializer
1512 switch (Ty->getTypeID()) {
1513 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001514 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001515 const ConstantInt* Int = cast<ConstantInt>(C);
1516 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1517 break;
1518 }
1519 case Type::FloatTyID:
1520 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001521 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001522 const ConstantFP* FP = cast<ConstantFP>(C);
1523 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001524 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001525 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001526 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001527 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001528 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001529 break;
1530 }
1531 case Type::ArrayTyID:
1532 case Type::VectorTyID:
1533 case Type::StructTyID:
1534 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1535 if (I!=0) Out << ",\n";
1536 printStaticConstant(C->getOperand(I),Offset);
1537 }
1538 break;
1539 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001540 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001541 // Initialize with global variable address
1542 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1543 std::string name = getValueName(G);
1544 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1545 } else {
1546 // Dynamic initialization
1547 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1548 InitListPtr->push_back(StaticInitializer(C,Offset));
1549 // Null pointer initialization
1550 if (TySize==4) Out << "int32 (0)";
1551 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001552 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001553 }
1554 break;
1555 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001556 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001557 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001558 }
1559 // Increase offset.
1560 Offset += TySize;
1561}
1562
1563
1564void MSILWriter::printStaticInitializer(const Constant* C,
1565 const std::string& Name) {
1566 switch (C->getType()->getTypeID()) {
1567 case Type::IntegerTyID:
1568 case Type::FloatTyID:
1569 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001570 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001571 break;
1572 case Type::ArrayTyID:
1573 case Type::VectorTyID:
1574 case Type::StructTyID:
1575 case Type::PointerTyID:
1576 Out << getTypeName(C->getType());
1577 break;
1578 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001579 errs() << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001580 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001581 }
1582 // Print initializer
1583 std::string label = Name;
1584 label.insert(label.length()-1,"$data");
1585 Out << Name << " at " << label << '\n';
1586 Out << ".data " << label << " = {\n";
1587 uint64_t offset = 0;
1588 printStaticConstant(C,offset);
1589 Out << "\n}\n\n";
1590}
1591
1592
1593void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1594 const Constant* C = G->getInitializer();
1595 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1596 InitListPtr = 0;
1597 else
1598 InitListPtr = &StaticInitList[G];
1599 printStaticInitializer(C,getValueName(G));
1600}
1601
1602
1603void MSILWriter::printGlobalVariables() {
1604 if (ModulePtr->global_empty()) return;
1605 Module::global_iterator I,E;
1606 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1607 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001608 Out << ".field static " << (I->isDeclaration() ? "public " :
1609 "private ");
1610 if (I->isDeclaration()) {
1611 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1612 } else
1613 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001614 }
1615}
1616
1617
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001618const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001619 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001620}
1621
1622
1623const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001624 return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001625}
1626
1627
Daniel Dunbarbda96532009-07-21 08:57:31 +00001628const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1629 bool isFunction,
1630 unsigned CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001631 // TODO: Read *.def file with function and libraries definitions.
1632 return "MSVCRT.DLL";
1633}
1634
1635
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001636void MSILWriter::printExternals() {
1637 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001638 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001639 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1640 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001641 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001642 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001643 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001644 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001645 std::string Sig =
1646 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1647 Out << ".method static hidebysig pinvokeimpl(\""
1648 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001649 }
1650 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001651 // External variables and static initialization.
1652 Out <<
1653 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1654 " native int LoadLibrary(string) preservesig {}\n"
1655 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1656 " native int GetProcAddress(native int, string) preservesig {}\n";
1657 Out <<
1658 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1659 " managed cil\n{\n"
1660 "\tldarg\tlib\n"
1661 "\tcall\tnative int LoadLibrary(string)\n"
1662 "\tldarg\tsym\n"
1663 "\tcall\tnative int GetProcAddress(native int,string)\n"
1664 "\tdup\n"
1665 "\tbrtrue\tL_01\n"
1666 "\tldstr\t\"Can no import variable\"\n"
1667 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1668 "\tthrow\n"
1669 "L_01:\n"
1670 "\tret\n"
1671 "}\n\n"
1672 ".method static private void $MSIL_Init() managed cil\n{\n";
1673 printStaticInitializerList();
1674 // Foreach global variable.
1675 for (Module::global_iterator I = ModulePtr->global_begin(),
1676 E = ModulePtr->global_end(); I!=E; ++I) {
1677 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1678 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1679 std::string Label = "not_null$_"+utostr(getUniqID());
1680 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1681 printSimpleInstruction("ldsflda",Tmp.c_str());
1682 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001683 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001684 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1685 printIndirectSave(I->getType());
1686 }
1687 printSimpleInstruction("ret");
1688 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001689}
1690
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001691
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001692//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001693// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001694//===----------------------------------------------------------------------===//
1695
David Greene71847812009-07-14 20:18:05 +00001696bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1697 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001698 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001699 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001700{
1701 if (FileType != TargetMachine::AssemblyFile) return true;
1702 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001703 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001704 PM.add(createLowerAllocationsPass(true));
1705 // FIXME: Handle switch trougth native IL instruction "switch"
1706 PM.add(createLowerSwitchPass());
1707 PM.add(createCFGSimplificationPass());
1708 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1709 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001710 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001711 return false;
1712}