Introduce new linkage types linkonce_odr, weak_odr, common_odr
[oota-llvm.git] / lib / Target / ARM / AsmPrinter / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - ARM LLVM assembly writer ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format ARM assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "ARM.h"
17 #include "ARMTargetMachine.h"
18 #include "ARMAddressingModes.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Module.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSet.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cctype>
40 using namespace llvm;
41
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43
44 namespace {
45   class VISIBILITY_HIDDEN ARMAsmPrinter : public AsmPrinter {
46     DwarfWriter *DW;
47     MachineModuleInfo *MMI;
48
49     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
50     /// make the right decision when printing asm code for different targets.
51     const ARMSubtarget *Subtarget;
52
53     /// AFI - Keep a pointer to ARMFunctionInfo for the current
54     /// MachineFunction.
55     ARMFunctionInfo *AFI;
56
57     /// MCP - Keep a pointer to constantpool entries of the current
58     /// MachineFunction.
59     const MachineConstantPool *MCP;
60
61     /// We name each basic block in a Function with a unique number, so
62     /// that we can consistently refer to them later. This is cleared
63     /// at the beginning of each call to runOnMachineFunction().
64     ///
65     typedef std::map<const Value *, unsigned> ValueMapTy;
66     ValueMapTy NumberForBB;
67
68     /// GVNonLazyPtrs - Keeps the set of GlobalValues that require
69     /// non-lazy-pointers for indirect access.
70     StringSet<> GVNonLazyPtrs;
71
72     /// HiddenGVNonLazyPtrs - Keeps the set of GlobalValues with hidden
73     /// visibility that require non-lazy-pointers for indirect access.
74     StringSet<> HiddenGVNonLazyPtrs;
75
76     /// FnStubs - Keeps the set of external function GlobalAddresses that the
77     /// asm printer should generate stubs for.
78     StringSet<> FnStubs;
79
80     /// True if asm printer is printing a series of CONSTPOOL_ENTRY.
81     bool InCPMode;
82   public:
83     ARMAsmPrinter(raw_ostream &O, TargetMachine &TM,
84                   const TargetAsmInfo *T, bool F)
85       : AsmPrinter(O, TM, T, F), DW(0), MMI(NULL), AFI(NULL), MCP(NULL),
86         InCPMode(false) {
87       Subtarget = &TM.getSubtarget<ARMSubtarget>();
88     }
89
90     virtual const char *getPassName() const {
91       return "ARM Assembly Printer";
92     }
93
94     void printOperand(const MachineInstr *MI, int opNum,
95                       const char *Modifier = 0);
96     void printSOImmOperand(const MachineInstr *MI, int opNum);
97     void printSOImm2PartOperand(const MachineInstr *MI, int opNum);
98     void printSORegOperand(const MachineInstr *MI, int opNum);
99     void printAddrMode2Operand(const MachineInstr *MI, int OpNo);
100     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNo);
101     void printAddrMode3Operand(const MachineInstr *MI, int OpNo);
102     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNo);
103     void printAddrMode4Operand(const MachineInstr *MI, int OpNo,
104                                const char *Modifier = 0);
105     void printAddrMode5Operand(const MachineInstr *MI, int OpNo,
106                                const char *Modifier = 0);
107     void printAddrModePCOperand(const MachineInstr *MI, int OpNo,
108                                 const char *Modifier = 0);
109     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNo);
110     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNo,
111                                       unsigned Scale);
112     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNo);
113     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNo);
114     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNo);
115     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNo);
116     void printPredicateOperand(const MachineInstr *MI, int opNum);
117     void printSBitModifierOperand(const MachineInstr *MI, int opNum);
118     void printPCLabel(const MachineInstr *MI, int opNum);
119     void printRegisterList(const MachineInstr *MI, int opNum);
120     void printCPInstOperand(const MachineInstr *MI, int opNum,
121                             const char *Modifier);
122     void printJTBlockOperand(const MachineInstr *MI, int opNum);
123
124     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
125                                  unsigned AsmVariant, const char *ExtraCode);
126
127     void printModuleLevelGV(const GlobalVariable* GVar);
128     bool printInstruction(const MachineInstr *MI);  // autogenerated.
129     void printMachineInstruction(const MachineInstr *MI);
130     bool runOnMachineFunction(MachineFunction &F);
131     bool doInitialization(Module &M);
132     bool doFinalization(Module &M);
133
134     /// EmitMachineConstantPoolValue - Print a machine constantpool value to
135     /// the .s file.
136     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
137       printDataDirective(MCPV->getType());
138
139       ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
140       GlobalValue *GV = ACPV->getGV();
141       std::string Name = GV ? Mang->getValueName(GV) : TAI->getGlobalPrefix();
142       if (!GV)
143         Name += ACPV->getSymbol();
144       if (ACPV->isNonLazyPointer()) {
145         if (GV->hasHiddenVisibility())
146           HiddenGVNonLazyPtrs.insert(Name);
147         else
148           GVNonLazyPtrs.insert(Name);
149         printSuffixedName(Name, "$non_lazy_ptr");
150       } else if (ACPV->isStub()) {
151         FnStubs.insert(Name);
152         printSuffixedName(Name, "$stub");
153       } else
154         O << Name;
155       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
156       if (ACPV->getPCAdjustment() != 0) {
157         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
158           << utostr(ACPV->getLabelId())
159           << "+" << (unsigned)ACPV->getPCAdjustment();
160          if (ACPV->mustAddCurrentAddress())
161            O << "-.";
162          O << ")";
163       }
164       O << "\n";
165
166       // If the constant pool value is a extern weak symbol, remember to emit
167       // the weak reference.
168       if (GV && GV->hasExternalWeakLinkage())
169         ExtWeakSymbols.insert(GV);
170     }
171     
172     void getAnalysisUsage(AnalysisUsage &AU) const {
173       AsmPrinter::getAnalysisUsage(AU);
174       AU.setPreservesAll();
175       AU.addRequired<MachineModuleInfo>();
176       AU.addRequired<DwarfWriter>();
177     }
178   };
179 } // end of anonymous namespace
180
181 #include "ARMGenAsmWriter.inc"
182
183 /// runOnMachineFunction - This uses the printInstruction()
184 /// method to print assembly for each instruction.
185 ///
186 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
187   this->MF = &MF;
188
189   AFI = MF.getInfo<ARMFunctionInfo>();
190   MCP = MF.getConstantPool();
191
192   SetupMachineFunction(MF);
193   O << "\n";
194
195   // NOTE: we don't print out constant pools here, they are handled as
196   // instructions.
197
198   O << "\n";
199   // Print out labels for the function.
200   const Function *F = MF.getFunction();
201   switch (F->getLinkage()) {
202   default: assert(0 && "Unknown linkage type!");
203   case Function::PrivateLinkage:
204   case Function::InternalLinkage:
205     SwitchToTextSection("\t.text", F);
206     break;
207   case Function::ExternalLinkage:
208     SwitchToTextSection("\t.text", F);
209     O << "\t.globl\t" << CurrentFnName << "\n";
210     break;
211   case Function::WeakAnyLinkage:
212   case Function::WeakODRLinkage:
213   case Function::LinkOnceAnyLinkage:
214   case Function::LinkOnceODRLinkage:
215     if (Subtarget->isTargetDarwin()) {
216       SwitchToTextSection(
217                 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
218       O << "\t.globl\t" << CurrentFnName << "\n";
219       O << "\t.weak_definition\t" << CurrentFnName << "\n";
220     } else {
221       O << TAI->getWeakRefDirective() << CurrentFnName << "\n";
222     }
223     break;
224   }
225
226   printVisibility(CurrentFnName, F->getVisibility());
227
228   if (AFI->isThumbFunction()) {
229     EmitAlignment(1, F, AFI->getAlign());
230     O << "\t.code\t16\n";
231     O << "\t.thumb_func";
232     if (Subtarget->isTargetDarwin())
233       O << "\t" << CurrentFnName;
234     O << "\n";
235     InCPMode = false;
236   } else
237     EmitAlignment(2, F);
238
239   O << CurrentFnName << ":\n";
240   // Emit pre-function debug information.
241   DW->BeginFunction(&MF);
242
243   if (Subtarget->isTargetDarwin()) {
244     // If the function is empty, then we need to emit *something*. Otherwise,
245     // the function's label might be associated with something that it wasn't
246     // meant to be associated with. We emit a noop in this situation.
247     MachineFunction::iterator I = MF.begin();
248
249     if (++I == MF.end() && MF.front().empty())
250       O << "\tnop\n";
251   }
252
253   // Print out code for the function.
254   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
255        I != E; ++I) {
256     // Print a label for the basic block.
257     if (I != MF.begin()) {
258       printBasicBlockLabel(I, true, true);
259       O << '\n';
260     }
261     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
262          II != E; ++II) {
263       // Print the assembly for the instruction.
264       printMachineInstruction(II);
265     }
266   }
267
268   if (TAI->hasDotTypeDotSizeDirective())
269     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
270
271   // Emit post-function debug information.
272   DW->EndFunction(&MF);
273
274   O.flush();
275
276   return false;
277 }
278
279 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
280                                  const char *Modifier) {
281   const MachineOperand &MO = MI->getOperand(opNum);
282   switch (MO.getType()) {
283   case MachineOperand::MO_Register:
284     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
285       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
286     else
287       assert(0 && "not implemented");
288     break;
289   case MachineOperand::MO_Immediate: {
290     if (!Modifier || strcmp(Modifier, "no_hash") != 0)
291       O << "#";
292
293     O << (int)MO.getImm();
294     break;
295   }
296   case MachineOperand::MO_MachineBasicBlock:
297     printBasicBlockLabel(MO.getMBB());
298     return;
299   case MachineOperand::MO_GlobalAddress: {
300     bool isCallOp = Modifier && !strcmp(Modifier, "call");
301     GlobalValue *GV = MO.getGlobal();
302     std::string Name = Mang->getValueName(GV);
303     bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
304                   GV->hasLinkOnceLinkage());
305     if (isExt && isCallOp && Subtarget->isTargetDarwin() &&
306         TM.getRelocationModel() != Reloc::Static) {
307       printSuffixedName(Name, "$stub");
308       FnStubs.insert(Name);
309     } else
310       O << Name;
311
312     printOffset(MO.getOffset());
313
314     if (isCallOp && Subtarget->isTargetELF() &&
315         TM.getRelocationModel() == Reloc::PIC_)
316       O << "(PLT)";
317     if (GV->hasExternalWeakLinkage())
318       ExtWeakSymbols.insert(GV);
319     break;
320   }
321   case MachineOperand::MO_ExternalSymbol: {
322     bool isCallOp = Modifier && !strcmp(Modifier, "call");
323     std::string Name(TAI->getGlobalPrefix());
324     Name += MO.getSymbolName();
325     if (isCallOp && Subtarget->isTargetDarwin() &&
326         TM.getRelocationModel() != Reloc::Static) {
327       printSuffixedName(Name, "$stub");
328       FnStubs.insert(Name);
329     } else
330       O << Name;
331     if (isCallOp && Subtarget->isTargetELF() &&
332         TM.getRelocationModel() == Reloc::PIC_)
333       O << "(PLT)";
334     break;
335   }
336   case MachineOperand::MO_ConstantPoolIndex:
337     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
338       << '_' << MO.getIndex();
339     break;
340   case MachineOperand::MO_JumpTableIndex:
341     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
342       << '_' << MO.getIndex();
343     break;
344   default:
345     O << "<unknown operand type>"; abort (); break;
346   }
347 }
348
349 static void printSOImm(raw_ostream &O, int64_t V, const TargetAsmInfo *TAI) {
350   assert(V < (1 << 12) && "Not a valid so_imm value!");
351   unsigned Imm = ARM_AM::getSOImmValImm(V);
352   unsigned Rot = ARM_AM::getSOImmValRot(V);
353
354   // Print low-level immediate formation info, per
355   // A5.1.3: "Data-processing operands - Immediate".
356   if (Rot) {
357     O << "#" << Imm << ", " << Rot;
358     // Pretty printed version.
359     O << ' ' << TAI->getCommentString() << ' ' << (int)ARM_AM::rotr32(Imm, Rot);
360   } else {
361     O << "#" << Imm;
362   }
363 }
364
365 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
366 /// immediate in bits 0-7.
367 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
368   const MachineOperand &MO = MI->getOperand(OpNum);
369   assert(MO.isImm() && "Not a valid so_imm value!");
370   printSOImm(O, MO.getImm(), TAI);
371 }
372
373 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
374 /// followed by an 'orr' to materialize.
375 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum) {
376   const MachineOperand &MO = MI->getOperand(OpNum);
377   assert(MO.isImm() && "Not a valid so_imm value!");
378   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
379   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
380   printSOImm(O, ARM_AM::getSOImmVal(V1), TAI);
381   O << "\n\torr";
382   printPredicateOperand(MI, 2);
383   O << " ";
384   printOperand(MI, 0); 
385   O << ", ";
386   printOperand(MI, 0); 
387   O << ", ";
388   printSOImm(O, ARM_AM::getSOImmVal(V2), TAI);
389 }
390
391 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
392 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
393 //    REG 0   0    - e.g. R5
394 //    REG REG 0,SH_OPC     - e.g. R5, ROR R3
395 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
396 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op) {
397   const MachineOperand &MO1 = MI->getOperand(Op);
398   const MachineOperand &MO2 = MI->getOperand(Op+1);
399   const MachineOperand &MO3 = MI->getOperand(Op+2);
400
401   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
402   O << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
403
404   // Print the shift opc.
405   O << ", "
406     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
407     << " ";
408
409   if (MO2.getReg()) {
410     assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
411     O << TM.getRegisterInfo()->get(MO2.getReg()).AsmName;
412     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
413   } else {
414     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
415   }
416 }
417
418 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
419   const MachineOperand &MO1 = MI->getOperand(Op);
420   const MachineOperand &MO2 = MI->getOperand(Op+1);
421   const MachineOperand &MO3 = MI->getOperand(Op+2);
422
423   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
424     printOperand(MI, Op);
425     return;
426   }
427
428   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
429
430   if (!MO2.getReg()) {
431     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
432       O << ", #"
433         << (char)ARM_AM::getAM2Op(MO3.getImm())
434         << ARM_AM::getAM2Offset(MO3.getImm());
435     O << "]";
436     return;
437   }
438
439   O << ", "
440     << (char)ARM_AM::getAM2Op(MO3.getImm())
441     << TM.getRegisterInfo()->get(MO2.getReg()).AsmName;
442   
443   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
444     O << ", "
445       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
446       << " #" << ShImm;
447   O << "]";
448 }
449
450 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
451   const MachineOperand &MO1 = MI->getOperand(Op);
452   const MachineOperand &MO2 = MI->getOperand(Op+1);
453
454   if (!MO1.getReg()) {
455     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
456     assert(ImmOffs && "Malformed indexed load / store!");
457     O << "#"
458       << (char)ARM_AM::getAM2Op(MO2.getImm())
459       << ImmOffs;
460     return;
461   }
462
463   O << (char)ARM_AM::getAM2Op(MO2.getImm())
464     << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
465   
466   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
467     O << ", "
468       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
469       << " #" << ShImm;
470 }
471
472 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
473   const MachineOperand &MO1 = MI->getOperand(Op);
474   const MachineOperand &MO2 = MI->getOperand(Op+1);
475   const MachineOperand &MO3 = MI->getOperand(Op+2);
476   
477   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
478   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
479
480   if (MO2.getReg()) {
481     O << ", "
482       << (char)ARM_AM::getAM3Op(MO3.getImm())
483       << TM.getRegisterInfo()->get(MO2.getReg()).AsmName
484       << "]";
485     return;
486   }
487   
488   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
489     O << ", #"
490       << (char)ARM_AM::getAM3Op(MO3.getImm())
491       << ImmOffs;
492   O << "]";
493 }
494
495 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
496   const MachineOperand &MO1 = MI->getOperand(Op);
497   const MachineOperand &MO2 = MI->getOperand(Op+1);
498
499   if (MO1.getReg()) {
500     O << (char)ARM_AM::getAM3Op(MO2.getImm())
501       << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
502     return;
503   }
504
505   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
506   assert(ImmOffs && "Malformed indexed load / store!");
507   O << "#"
508     << (char)ARM_AM::getAM3Op(MO2.getImm())
509     << ImmOffs;
510 }
511   
512 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
513                                           const char *Modifier) {
514   const MachineOperand &MO1 = MI->getOperand(Op);
515   const MachineOperand &MO2 = MI->getOperand(Op+1);
516   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
517   if (Modifier && strcmp(Modifier, "submode") == 0) {
518     if (MO1.getReg() == ARM::SP) {
519       bool isLDM = (MI->getOpcode() == ARM::LDM ||
520                     MI->getOpcode() == ARM::LDM_RET);
521       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
522     } else
523       O << ARM_AM::getAMSubModeStr(Mode);
524   } else {
525     printOperand(MI, Op);
526     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
527       O << "!";
528   }
529 }
530
531 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
532                                           const char *Modifier) {
533   const MachineOperand &MO1 = MI->getOperand(Op);
534   const MachineOperand &MO2 = MI->getOperand(Op+1);
535
536   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
537     printOperand(MI, Op);
538     return;
539   }
540   
541   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
542
543   if (Modifier && strcmp(Modifier, "submode") == 0) {
544     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
545     if (MO1.getReg() == ARM::SP) {
546       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
547                      MI->getOpcode() == ARM::FLDMS);
548       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
549     } else
550       O << ARM_AM::getAMSubModeStr(Mode);
551     return;
552   } else if (Modifier && strcmp(Modifier, "base") == 0) {
553     // Used for FSTM{D|S} and LSTM{D|S} operations.
554     O << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
555     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
556       O << "!";
557     return;
558   }
559   
560   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
561   
562   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
563     O << ", #"
564       << (char)ARM_AM::getAM5Op(MO2.getImm())
565       << ImmOffs*4;
566   }
567   O << "]";
568 }
569
570 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
571                                            const char *Modifier) {
572   if (Modifier && strcmp(Modifier, "label") == 0) {
573     printPCLabel(MI, Op+1);
574     return;
575   }
576
577   const MachineOperand &MO1 = MI->getOperand(Op);
578   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
579   O << "[pc, +" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName << "]";
580 }
581
582 void
583 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
584   const MachineOperand &MO1 = MI->getOperand(Op);
585   const MachineOperand &MO2 = MI->getOperand(Op+1);
586   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
587   O << ", " << TM.getRegisterInfo()->get(MO2.getReg()).AsmName << "]";
588 }
589
590 void
591 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
592                                             unsigned Scale) {
593   const MachineOperand &MO1 = MI->getOperand(Op);
594   const MachineOperand &MO2 = MI->getOperand(Op+1);
595   const MachineOperand &MO3 = MI->getOperand(Op+2);
596
597   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
598     printOperand(MI, Op);
599     return;
600   }
601
602   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
603   if (MO3.getReg())
604     O << ", " << TM.getRegisterInfo()->get(MO3.getReg()).AsmName;
605   else if (unsigned ImmOffs = MO2.getImm()) {
606     O << ", #" << ImmOffs;
607     if (Scale > 1)
608       O << " * " << Scale;
609   }
610   O << "]";
611 }
612
613 void
614 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
615   printThumbAddrModeRI5Operand(MI, Op, 1);
616 }
617 void
618 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
619   printThumbAddrModeRI5Operand(MI, Op, 2);
620 }
621 void
622 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
623   printThumbAddrModeRI5Operand(MI, Op, 4);
624 }
625
626 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
627   const MachineOperand &MO1 = MI->getOperand(Op);
628   const MachineOperand &MO2 = MI->getOperand(Op+1);
629   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
630   if (unsigned ImmOffs = MO2.getImm())
631     O << ", #" << ImmOffs << " * 4";
632   O << "]";
633 }
634
635 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int opNum) {
636   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(opNum).getImm();
637   if (CC != ARMCC::AL)
638     O << ARMCondCodeToString(CC);
639 }
640
641 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int opNum){
642   unsigned Reg = MI->getOperand(opNum).getReg();
643   if (Reg) {
644     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
645     O << 's';
646   }
647 }
648
649 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int opNum) {
650   int Id = (int)MI->getOperand(opNum).getImm();
651   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
652 }
653
654 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int opNum) {
655   O << "{";
656   for (unsigned i = opNum, e = MI->getNumOperands(); i != e; ++i) {
657     printOperand(MI, i);
658     if (i != e-1) O << ", ";
659   }
660   O << "}";
661 }
662
663 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNo,
664                                        const char *Modifier) {
665   assert(Modifier && "This operand only works with a modifier!");
666   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
667   // data itself.
668   if (!strcmp(Modifier, "label")) {
669     unsigned ID = MI->getOperand(OpNo).getImm();
670     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
671       << '_' << ID << ":\n";
672   } else {
673     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
674     unsigned CPI = MI->getOperand(OpNo).getIndex();
675
676     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
677     
678     if (MCPE.isMachineConstantPoolEntry()) {
679       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
680     } else {
681       EmitGlobalConstant(MCPE.Val.ConstVal);
682       // remember to emit the weak reference
683       if (const GlobalValue *GV = dyn_cast<GlobalValue>(MCPE.Val.ConstVal))
684         if (GV->hasExternalWeakLinkage())
685           ExtWeakSymbols.insert(GV);
686     }
687   }
688 }
689
690 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNo) {
691   const MachineOperand &MO1 = MI->getOperand(OpNo);
692   const MachineOperand &MO2 = MI->getOperand(OpNo+1); // Unique Id
693   unsigned JTI = MO1.getIndex();
694   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
695     << '_' << JTI << '_' << MO2.getImm() << ":\n";
696
697   const char *JTEntryDirective = TAI->getJumpTableDirective();
698   if (!JTEntryDirective)
699     JTEntryDirective = TAI->getData32bitsDirective();
700
701   const MachineFunction *MF = MI->getParent()->getParent();
702   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
703   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
704   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
705   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
706   std::set<MachineBasicBlock*> JTSets;
707   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
708     MachineBasicBlock *MBB = JTBBs[i];
709     if (UseSet && JTSets.insert(MBB).second)
710       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
711
712     O << JTEntryDirective << ' ';
713     if (UseSet)
714       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
715         << '_' << JTI << '_' << MO2.getImm()
716         << "_set_" << MBB->getNumber();
717     else if (TM.getRelocationModel() == Reloc::PIC_) {
718       printBasicBlockLabel(MBB, false, false, false);
719       // If the arch uses custom Jump Table directives, don't calc relative to JT
720       if (!TAI->getJumpTableDirective()) 
721         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
722           << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
723     } else
724       printBasicBlockLabel(MBB, false, false, false);
725     if (i != e-1)
726       O << '\n';
727   }
728 }
729
730
731 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
732                                     unsigned AsmVariant, const char *ExtraCode){
733   // Does this asm operand have a single letter operand modifier?
734   if (ExtraCode && ExtraCode[0]) {
735     if (ExtraCode[1] != 0) return true; // Unknown modifier.
736     
737     switch (ExtraCode[0]) {
738     default: return true;  // Unknown modifier.
739     case 'c': // Don't print "$" before a global var name or constant.
740     case 'P': // Print a VFP double precision register.
741       printOperand(MI, OpNo);
742       return false;
743     case 'Q':
744       if (TM.getTargetData()->isLittleEndian())
745         break;
746       // Fallthrough
747     case 'R':
748       if (TM.getTargetData()->isBigEndian())
749         break;
750       // Fallthrough
751     case 'H': // Write second word of DI / DF reference.  
752       // Verify that this operand has two consecutive registers.
753       if (!MI->getOperand(OpNo).isReg() ||
754           OpNo+1 == MI->getNumOperands() ||
755           !MI->getOperand(OpNo+1).isReg())
756         return true;
757       ++OpNo;   // Return the high-part.
758     }
759   }
760   
761   printOperand(MI, OpNo);
762   return false;
763 }
764
765 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
766   ++EmittedInsts;
767
768   int Opc = MI->getOpcode();
769   switch (Opc) {
770   case ARM::CONSTPOOL_ENTRY:
771     if (!InCPMode && AFI->isThumbFunction()) {
772       EmitAlignment(2);
773       InCPMode = true;
774     }
775     break;
776   default: {
777     if (InCPMode && AFI->isThumbFunction())
778       InCPMode = false;
779   }}
780
781   // Call the autogenerated instruction printer routines.
782   printInstruction(MI);
783 }
784
785 bool ARMAsmPrinter::doInitialization(Module &M) {
786
787   bool Result = AsmPrinter::doInitialization(M);
788
789   // Emit initial debug information.
790   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
791   assert(MMI);
792   DW = getAnalysisIfAvailable<DwarfWriter>();
793   assert(DW && "Dwarf Writer is not available");
794   DW->BeginModule(&M, MMI, O, this, TAI);
795
796   // Darwin wants symbols to be quoted if they have complex names.
797   if (Subtarget->isTargetDarwin())
798     Mang->setUseQuotes(true);
799
800   return Result;
801 }
802
803 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
804 /// Don't print things like \\n or \\0.
805 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
806   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
807        Name != E; ++Name)
808     if (isprint(*Name))
809       OS << *Name;
810 }
811
812 void ARMAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
813   const TargetData *TD = TM.getTargetData();
814
815   if (!GVar->hasInitializer())   // External global require no code
816     return;
817
818   // Check to see if this is a special global used by LLVM, if so, emit it.
819
820   if (EmitSpecialLLVMGlobal(GVar)) {
821     if (Subtarget->isTargetDarwin() &&
822         TM.getRelocationModel() == Reloc::Static) {
823       if (GVar->getName() == "llvm.global_ctors")
824         O << ".reference .constructors_used\n";
825       else if (GVar->getName() == "llvm.global_dtors")
826         O << ".reference .destructors_used\n";
827     }
828     return;
829   }
830
831   std::string name = Mang->getValueName(GVar);
832   Constant *C = GVar->getInitializer();
833   const Type *Type = C->getType();
834   unsigned Size = TD->getTypePaddedSize(Type);
835   unsigned Align = TD->getPreferredAlignmentLog(GVar);
836   bool isDarwin = Subtarget->isTargetDarwin();
837
838   printVisibility(name, GVar->getVisibility());
839
840   if (Subtarget->isTargetELF())
841     O << "\t.type " << name << ",%object\n";
842
843   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal() &&
844       !(isDarwin &&
845         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
846     // FIXME: This seems to be pretty darwin-specific
847
848     if (GVar->hasExternalLinkage()) {
849       SwitchToSection(TAI->SectionForGlobal(GVar));
850       if (const char *Directive = TAI->getZeroFillDirective()) {
851         O << "\t.globl\t" << name << "\n";
852         O << Directive << "__DATA, __common, " << name << ", "
853           << Size << ", " << Align << "\n";
854         return;
855       }
856     }
857
858     if (GVar->hasLocalLinkage() || GVar->isWeakForLinker()) {
859       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
860
861       if (isDarwin) {
862         if (GVar->hasLocalLinkage()) {
863           O << TAI->getLCOMMDirective()  << name << "," << Size
864             << ',' << Align;
865         } else if (GVar->hasCommonLinkage()) {
866           O << TAI->getCOMMDirective()  << name << "," << Size
867             << ',' << Align;
868         } else {
869           SwitchToSection(TAI->SectionForGlobal(GVar));
870           O << "\t.globl " << name << '\n'
871             << TAI->getWeakDefDirective() << name << '\n';
872           EmitAlignment(Align, GVar);
873           O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
874           PrintUnmangledNameSafely(GVar, O);
875           O << '\n';
876           EmitGlobalConstant(C);
877           return;
878         }
879       } else if (TAI->getLCOMMDirective() != NULL) {
880         if (GVar->hasLocalLinkage()) {
881           O << TAI->getLCOMMDirective() << name << "," << Size;
882         } else {
883           O << TAI->getCOMMDirective()  << name << "," << Size;
884           if (TAI->getCOMMDirectiveTakesAlignment())
885             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
886         }
887       } else {
888         SwitchToSection(TAI->SectionForGlobal(GVar));
889         if (GVar->hasLocalLinkage())
890           O << "\t.local\t" << name << "\n";
891         O << TAI->getCOMMDirective()  << name << "," << Size;
892         if (TAI->getCOMMDirectiveTakesAlignment())
893           O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
894       }
895       O << "\t\t" << TAI->getCommentString() << " ";
896       PrintUnmangledNameSafely(GVar, O);
897       O << "\n";
898       return;
899     }
900   }
901
902   SwitchToSection(TAI->SectionForGlobal(GVar));
903   switch (GVar->getLinkage()) {
904    case GlobalValue::CommonAnyLinkage:
905    case GlobalValue::CommonODRLinkage:
906    case GlobalValue::LinkOnceAnyLinkage:
907    case GlobalValue::LinkOnceODRLinkage:
908    case GlobalValue::WeakAnyLinkage:
909    case GlobalValue::WeakODRLinkage:
910     if (isDarwin) {
911       O << "\t.globl " << name << "\n"
912         << "\t.weak_definition " << name << "\n";
913     } else {
914       O << "\t.weak " << name << "\n";
915     }
916     break;
917    case GlobalValue::AppendingLinkage:
918     // FIXME: appending linkage variables should go into a section of
919     // their name or something.  For now, just emit them as external.
920    case GlobalValue::ExternalLinkage:
921     O << "\t.globl " << name << "\n";
922     // FALL THROUGH
923    case GlobalValue::PrivateLinkage:
924    case GlobalValue::InternalLinkage:
925     break;
926    default:
927     assert(0 && "Unknown linkage type!");
928     break;
929   }
930
931   EmitAlignment(Align, GVar);
932   O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
933   PrintUnmangledNameSafely(GVar, O);
934   O << "\n";
935   if (TAI->hasDotTypeDotSizeDirective())
936     O << "\t.size " << name << ", " << Size << "\n";
937
938   // If the initializer is a extern weak symbol, remember to emit the weak
939   // reference!
940   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
941     if (GV->hasExternalWeakLinkage())
942       ExtWeakSymbols.insert(GV);
943
944   EmitGlobalConstant(C);
945   O << '\n';
946 }
947
948
949 bool ARMAsmPrinter::doFinalization(Module &M) {
950   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
951        I != E; ++I)
952     printModuleLevelGV(I);
953
954   if (Subtarget->isTargetDarwin()) {
955     SwitchToDataSection("");
956
957     // Output stubs for dynamically-linked functions
958     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
959          i != e; ++i) {
960       if (TM.getRelocationModel() == Reloc::PIC_)
961         SwitchToTextSection(".section __TEXT,__picsymbolstub4,symbol_stubs,"
962                             "none,16", 0);
963       else
964         SwitchToTextSection(".section __TEXT,__symbol_stub4,symbol_stubs,"
965                             "none,12", 0);
966
967       EmitAlignment(2);
968       O << "\t.code\t32\n";
969
970       const char *p = i->getKeyData();
971       printSuffixedName(p, "$stub");
972       O << ":\n";
973       O << "\t.indirect_symbol " << p << "\n";
974       O << "\tldr ip, ";
975       printSuffixedName(p, "$slp");
976       O << "\n";
977       if (TM.getRelocationModel() == Reloc::PIC_) {
978         printSuffixedName(p, "$scv");
979         O << ":\n";
980         O << "\tadd ip, pc, ip\n";
981       }
982       O << "\tldr pc, [ip, #0]\n";
983       printSuffixedName(p, "$slp");
984       O << ":\n";
985       O << "\t.long\t";
986       printSuffixedName(p, "$lazy_ptr");
987       if (TM.getRelocationModel() == Reloc::PIC_) {
988         O << "-(";
989         printSuffixedName(p, "$scv");
990         O << "+8)\n";
991       } else
992         O << "\n";
993       SwitchToDataSection(".lazy_symbol_pointer", 0);
994       printSuffixedName(p, "$lazy_ptr");
995       O << ":\n";
996       O << "\t.indirect_symbol " << p << "\n";
997       O << "\t.long\tdyld_stub_binding_helper\n";
998     }
999     O << "\n";
1000
1001     // Output non-lazy-pointers for external and common global variables.
1002     if (!GVNonLazyPtrs.empty()) {
1003       SwitchToDataSection("\t.non_lazy_symbol_pointer", 0);
1004       for (StringSet<>::iterator i =  GVNonLazyPtrs.begin(),
1005              e = GVNonLazyPtrs.end(); i != e; ++i) {
1006         const char *p = i->getKeyData();
1007         printSuffixedName(p, "$non_lazy_ptr");
1008         O << ":\n";
1009         O << "\t.indirect_symbol " << p << "\n";
1010         O << "\t.long\t0\n";
1011       }
1012     }
1013
1014     if (!HiddenGVNonLazyPtrs.empty()) {
1015       SwitchToSection(TAI->getDataSection());
1016       for (StringSet<>::iterator i = HiddenGVNonLazyPtrs.begin(),
1017              e = HiddenGVNonLazyPtrs.end(); i != e; ++i) {
1018         const char *p = i->getKeyData();
1019         EmitAlignment(2);
1020         printSuffixedName(p, "$non_lazy_ptr");
1021         O << ":\n";
1022         O << "\t.long " << p << "\n";
1023       }
1024     }
1025
1026
1027     // Emit initial debug information.
1028     DW->EndModule();
1029
1030     // Funny Darwin hack: This flag tells the linker that no global symbols
1031     // contain code that falls through to other global symbols (e.g. the obvious
1032     // implementation of multiple entry points).  If this doesn't occur, the
1033     // linker can safely perform dead code stripping.  Since LLVM never
1034     // generates code that does this, it is always safe to set.
1035     O << "\t.subsections_via_symbols\n";
1036   } else {
1037     // Emit final debug information for ELF.
1038     DW->EndModule();
1039   }
1040
1041   return AsmPrinter::doFinalization(M);
1042 }
1043
1044 /// createARMCodePrinterPass - Returns a pass that prints the ARM
1045 /// assembly code for a MachineFunction to the given output stream,
1046 /// using the given target machine description.  This should work
1047 /// regardless of whether the function is in SSA form.
1048 ///
1049 FunctionPass *llvm::createARMCodePrinterPass(raw_ostream &o,
1050                                              ARMTargetMachine &tm,
1051                                              bool fast) {
1052   return new ARMAsmPrinter(o, tm, tm.getTargetAsmInfo(), fast);
1053 }
1054
1055 namespace {
1056   static struct Register {
1057     Register() {
1058       ARMTargetMachine::registerAsmPrinter(createARMCodePrinterPass);
1059     }
1060   } Registrator;
1061 }