llvm.org GIT mirror llvm / c2c50cd
Rename VMCore directory to IR. Aside from moving the actual files, this patch only updates the build system and the source file comments under lib/... that are relevant. I'll be updating other docs and other files in smaller subsequnet commits. While I've tried to test this, but it is entirely possible that there will still be some build system fallout. Also, note that I've not changed the library name itself: libLLVMCore.a is still the library name. I'd be interested in others' opinions about whether we should rename this as well (I think we should, just not sure what it might break) git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@171359 91177308-0d34-0410-b5e6-96231b3b80d8 Chandler Carruth 7 years ago
102 changed file(s) with 30219 addition(s) and 30219 deletion(s). Raw diff Collapse all Expand all
88 //
99 // This file defines routines for folding instructions into constants.
1010 //
11 // Also, to supplement the basic VMCore ConstantExpr simplifications,
11 // Also, to supplement the basic IR ConstantExpr simplifications,
1212 // this file defines some additional folding routines that can make use of
13 // DataLayout information. These functions cannot go in VMCore due to library
13 // DataLayout information. These functions cannot go in IR due to library
1414 // dependency issues.
1515 //
1616 //===----------------------------------------------------------------------===//
6767 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
6868 Type *SrcIVTy =
6969 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
70 // Ask VMCore to do the conversion now that #elts line up.
70 // Ask IR to do the conversion now that #elts line up.
7171 C = ConstantExpr::getBitCast(C, SrcIVTy);
7272 CDV = cast(C);
7373 }
103103 if (!isa(C) && !isa(C))
104104 return ConstantExpr::getBitCast(C, DestTy);
105105
106 // If the element types match, VMCore can fold it.
106 // If the element types match, IR can fold it.
107107 unsigned NumDstElt = DestVTy->getNumElements();
108108 unsigned NumSrcElt = C->getType()->getVectorNumElements();
109109 if (NumDstElt == NumSrcElt)
130130 // Recursively handle this integer conversion, if possible.
131131 C = FoldBitCast(C, DestIVTy, TD);
132132
133 // Finally, VMCore can handle this now that #elts line up.
133 // Finally, IR can handle this now that #elts line up.
134134 return ConstantExpr::getBitCast(C, DestTy);
135135 }
136136
140140 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
141141 Type *SrcIVTy =
142142 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
143 // Ask VMCore to do the conversion now that #elts line up.
143 // Ask IR to do the conversion now that #elts line up.
144144 C = ConstantExpr::getBitCast(C, SrcIVTy);
145 // If VMCore wasn't able to fold it, bail out.
145 // If IR wasn't able to fold it, bail out.
146146 if (!isa(C) && // FIXME: Remove ConstantVector.
147147 !isa(C))
148148 return C;
0 # `Support' and `TableGen' libraries are added on the top-level CMakeLists.txt
11
2 add_subdirectory(VMCore)
2 add_subdirectory(IR)
33 add_subdirectory(CodeGen)
44 add_subdirectory(Bitcode)
55 add_subdirectory(Transforms)
0 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This library implements the functionality defined in llvm/Assembly/Writer.h
10 //
11 // Note that these routines must be extremely tolerant of various errors in the
12 // LLVM code, because it can be used for debugging transformations.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
22 #include "llvm/Assembly/PrintModulePass.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/Module.h"
31 #include "llvm/Operator.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/TypeFinder.h"
39 #include "llvm/ValueSymbolTable.h"
40 #include
41 #include
42 using namespace llvm;
43
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
46
47 //===----------------------------------------------------------------------===//
48 // Helper Functions
49 //===----------------------------------------------------------------------===//
50
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
54
55 if (const BasicBlock *BB = dyn_cast(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
57
58 if (const Instruction *I = dyn_cast(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
61 }
62
63 if (const GlobalValue *GV = dyn_cast(V))
64 return GV->getParent();
65 return 0;
66 }
67
68 static void PrintCallingConv(unsigned cc, raw_ostream &Out)
69 {
70 switch (cc) {
71 case CallingConv::Fast: Out << "fastcc"; break;
72 case CallingConv::Cold: Out << "coldcc"; break;
73 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
74 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
75 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
76 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
77 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
78 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
79 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc"; break;
80 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
81 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
82 case CallingConv::PTX_Device: Out << "ptx_device"; break;
83 default: Out << "cc" << cc; break;
84 }
85 }
86
87 // PrintEscapedString - Print each character of the specified string, escaping
88 // it if it is not printable or if it is an escape char.
89 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
90 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
91 unsigned char C = Name[i];
92 if (isprint(C) && C != '\\' && C != '"')
93 Out << C;
94 else
95 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
96 }
97 }
98
99 enum PrefixType {
100 GlobalPrefix,
101 LabelPrefix,
102 LocalPrefix,
103 NoPrefix
104 };
105
106 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
107 /// prefixed with % (if the string only contains simple characters) or is
108 /// surrounded with ""'s (if it has special chars in it). Print it out.
109 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
110 assert(!Name.empty() && "Cannot get empty name!");
111 switch (Prefix) {
112 case NoPrefix: break;
113 case GlobalPrefix: OS << '@'; break;
114 case LabelPrefix: break;
115 case LocalPrefix: OS << '%'; break;
116 }
117
118 // Scan the name to see if it needs quotes first.
119 bool NeedsQuotes = isdigit(Name[0]);
120 if (!NeedsQuotes) {
121 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
122 // By making this unsigned, the value passed in to isalnum will always be
123 // in the range 0-255. This is important when building with MSVC because
124 // its implementation will assert. This situation can arise when dealing
125 // with UTF-8 multibyte characters.
126 unsigned char C = Name[i];
127 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
128 NeedsQuotes = true;
129 break;
130 }
131 }
132 }
133
134 // If we didn't need any quotes, just write out the name in one blast.
135 if (!NeedsQuotes) {
136 OS << Name;
137 return;
138 }
139
140 // Okay, we need quotes. Output the quotes and escape any scary characters as
141 // needed.
142 OS << '"';
143 PrintEscapedString(Name, OS);
144 OS << '"';
145 }
146
147 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
148 /// prefixed with % (if the string only contains simple characters) or is
149 /// surrounded with ""'s (if it has special chars in it). Print it out.
150 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
151 PrintLLVMName(OS, V->getName(),
152 isa(V) ? GlobalPrefix : LocalPrefix);
153 }
154
155 //===----------------------------------------------------------------------===//
156 // TypePrinting Class: Type printing machinery
157 //===----------------------------------------------------------------------===//
158
159 /// TypePrinting - Type printing machinery.
160 namespace {
161 class TypePrinting {
162 TypePrinting(const TypePrinting &) LLVM_DELETED_FUNCTION;
163 void operator=(const TypePrinting&) LLVM_DELETED_FUNCTION;
164 public:
165
166 /// NamedTypes - The named types that are used by the current module.
167 TypeFinder NamedTypes;
168
169 /// NumberedTypes - The numbered types, along with their value.
170 DenseMap NumberedTypes;
171
172
173 TypePrinting() {}
174 ~TypePrinting() {}
175
176 void incorporateTypes(const Module &M);
177
178 void print(Type *Ty, raw_ostream &OS);
179
180 void printStructBody(StructType *Ty, raw_ostream &OS);
181 };
182 } // end anonymous namespace.
183
184
185 void TypePrinting::incorporateTypes(const Module &M) {
186 NamedTypes.run(M, false);
187
188 // The list of struct types we got back includes all the struct types, split
189 // the unnamed ones out to a numbering and remove the anonymous structs.
190 unsigned NextNumber = 0;
191
192 std::vector::iterator NextToUse = NamedTypes.begin(), I, E;
193 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
194 StructType *STy = *I;
195
196 // Ignore anonymous types.
197 if (STy->isLiteral())
198 continue;
199
200 if (STy->getName().empty())
201 NumberedTypes[STy] = NextNumber++;
202 else
203 *NextToUse++ = STy;
204 }
205
206 NamedTypes.erase(NextToUse, NamedTypes.end());
207 }
208
209
210 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
211 /// use of type names or up references to shorten the type name where possible.
212 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
213 switch (Ty->getTypeID()) {
214 case Type::VoidTyID: OS << "void"; break;
215 case Type::HalfTyID: OS << "half"; break;
216 case Type::FloatTyID: OS << "float"; break;
217 case Type::DoubleTyID: OS << "double"; break;
218 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
219 case Type::FP128TyID: OS << "fp128"; break;
220 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
221 case Type::LabelTyID: OS << "label"; break;
222 case Type::MetadataTyID: OS << "metadata"; break;
223 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
224 case Type::IntegerTyID:
225 OS << 'i' << cast(Ty)->getBitWidth();
226 return;
227
228 case Type::FunctionTyID: {
229 FunctionType *FTy = cast(Ty);
230 print(FTy->getReturnType(), OS);
231 OS << " (";
232 for (FunctionType::param_iterator I = FTy->param_begin(),
233 E = FTy->param_end(); I != E; ++I) {
234 if (I != FTy->param_begin())
235 OS << ", ";
236 print(*I, OS);
237 }
238 if (FTy->isVarArg()) {
239 if (FTy->getNumParams()) OS << ", ";
240 OS << "...";
241 }
242 OS << ')';
243 return;
244 }
245 case Type::StructTyID: {
246 StructType *STy = cast(Ty);
247
248 if (STy->isLiteral())
249 return printStructBody(STy, OS);
250
251 if (!STy->getName().empty())
252 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
253
254 DenseMap::iterator I = NumberedTypes.find(STy);
255 if (I != NumberedTypes.end())
256 OS << '%' << I->second;
257 else // Not enumerated, print the hex address.
258 OS << "%\"type " << STy << '\"';
259 return;
260 }
261 case Type::PointerTyID: {
262 PointerType *PTy = cast(Ty);
263 print(PTy->getElementType(), OS);
264 if (unsigned AddressSpace = PTy->getAddressSpace())
265 OS << " addrspace(" << AddressSpace << ')';
266 OS << '*';
267 return;
268 }
269 case Type::ArrayTyID: {
270 ArrayType *ATy = cast(Ty);
271 OS << '[' << ATy->getNumElements() << " x ";
272 print(ATy->getElementType(), OS);
273 OS << ']';
274 return;
275 }
276 case Type::VectorTyID: {
277 VectorType *PTy = cast(Ty);
278 OS << "<" << PTy->getNumElements() << " x ";
279 print(PTy->getElementType(), OS);
280 OS << '>';
281 return;
282 }
283 default:
284 OS << "";
285 return;
286 }
287 }
288
289 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
290 if (STy->isOpaque()) {
291 OS << "opaque";
292 return;
293 }
294
295 if (STy->isPacked())
296 OS << '<';
297
298 if (STy->getNumElements() == 0) {
299 OS << "{}";
300 } else {
301 StructType::element_iterator I = STy->element_begin();
302 OS << "{ ";
303 print(*I++, OS);
304 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
305 OS << ", ";
306 print(*I, OS);
307 }
308
309 OS << " }";
310 }
311 if (STy->isPacked())
312 OS << '>';
313 }
314
315
316
317 //===----------------------------------------------------------------------===//
318 // SlotTracker Class: Enumerate slot numbers for unnamed values
319 //===----------------------------------------------------------------------===//
320
321 namespace {
322
323 /// This class provides computation of slot numbers for LLVM Assembly writing.
324 ///
325 class SlotTracker {
326 public:
327 /// ValueMap - A mapping of Values to slot numbers.
328 typedef DenseMap ValueMap;
329
330 private:
331 /// TheModule - The module for which we are holding slot numbers.
332 const Module* TheModule;
333
334 /// TheFunction - The function for which we are holding slot numbers.
335 const Function* TheFunction;
336 bool FunctionProcessed;
337
338 /// mMap - The slot map for the module level data.
339 ValueMap mMap;
340 unsigned mNext;
341
342 /// fMap - The slot map for the function level data.
343 ValueMap fMap;
344 unsigned fNext;
345
346 /// mdnMap - Map for MDNodes.
347 DenseMap mdnMap;
348 unsigned mdnNext;
349 public:
350 /// Construct from a module
351 explicit SlotTracker(const Module *M);
352 /// Construct from a function, starting out in incorp state.
353 explicit SlotTracker(const Function *F);
354
355 /// Return the slot number of the specified value in it's type
356 /// plane. If something is not in the SlotTracker, return -1.
357 int getLocalSlot(const Value *V);
358 int getGlobalSlot(const GlobalValue *V);
359 int getMetadataSlot(const MDNode *N);
360
361 /// If you'd like to deal with a function instead of just a module, use
362 /// this method to get its data into the SlotTracker.
363 void incorporateFunction(const Function *F) {
364 TheFunction = F;
365 FunctionProcessed = false;
366 }
367
368 /// After calling incorporateFunction, use this method to remove the
369 /// most recently incorporated function from the SlotTracker. This
370 /// will reset the state of the machine back to just the module contents.
371 void purgeFunction();
372
373 /// MDNode map iterators.
374 typedef DenseMap::iterator mdn_iterator;
375 mdn_iterator mdn_begin() { return mdnMap.begin(); }
376 mdn_iterator mdn_end() { return mdnMap.end(); }
377 unsigned mdn_size() const { return mdnMap.size(); }
378 bool mdn_empty() const { return mdnMap.empty(); }
379
380 /// This function does the actual initialization.
381 inline void initialize();
382
383 // Implementation Details
384 private:
385 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
386 void CreateModuleSlot(const GlobalValue *V);
387
388 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
389 void CreateMetadataSlot(const MDNode *N);
390
391 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
392 void CreateFunctionSlot(const Value *V);
393
394 /// Add all of the module level global variables (and their initializers)
395 /// and function declarations, but not the contents of those functions.
396 void processModule();
397
398 /// Add all of the functions arguments, basic blocks, and instructions.
399 void processFunction();
400
401 SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
402 void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
403 };
404
405 } // end anonymous namespace
406
407
408 static SlotTracker *createSlotTracker(const Value *V) {
409 if (const Argument *FA = dyn_cast(V))
410 return new SlotTracker(FA->getParent());
411
412 if (const Instruction *I = dyn_cast(V))
413 if (I->getParent())
414 return new SlotTracker(I->getParent()->getParent());
415
416 if (const BasicBlock *BB = dyn_cast(V))
417 return new SlotTracker(BB->getParent());
418
419 if (const GlobalVariable *GV = dyn_cast(V))
420 return new SlotTracker(GV->getParent());
421
422 if (const GlobalAlias *GA = dyn_cast(V))
423 return new SlotTracker(GA->getParent());
424
425 if (const Function *Func = dyn_cast(V))
426 return new SlotTracker(Func);
427
428 if (const MDNode *MD = dyn_cast(V)) {
429 if (!MD->isFunctionLocal())
430 return new SlotTracker(MD->getFunction());
431
432 return new SlotTracker((Function *)0);
433 }
434
435 return 0;
436 }
437
438 #if 0
439 #define ST_DEBUG(X) dbgs() << X
440 #else
441 #define ST_DEBUG(X)
442 #endif
443
444 // Module level constructor. Causes the contents of the Module (sans functions)
445 // to be added to the slot table.
446 SlotTracker::SlotTracker(const Module *M)
447 : TheModule(M), TheFunction(0), FunctionProcessed(false),
448 mNext(0), fNext(0), mdnNext(0) {
449 }
450
451 // Function level constructor. Causes the contents of the Module and the one
452 // function provided to be added to the slot table.
453 SlotTracker::SlotTracker(const Function *F)
454 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
455 mNext(0), fNext(0), mdnNext(0) {
456 }
457
458 inline void SlotTracker::initialize() {
459 if (TheModule) {
460 processModule();
461 TheModule = 0; ///< Prevent re-processing next time we're called.
462 }
463
464 if (TheFunction && !FunctionProcessed)
465 processFunction();
466 }
467
468 // Iterate through all the global variables, functions, and global
469 // variable initializers and create slots for them.
470 void SlotTracker::processModule() {
471 ST_DEBUG("begin processModule!\n");
472
473 // Add all of the unnamed global variables to the value table.
474 for (Module::const_global_iterator I = TheModule->global_begin(),
475 E = TheModule->global_end(); I != E; ++I) {
476 if (!I->hasName())
477 CreateModuleSlot(I);
478 }
479
480 // Add metadata used by named metadata.
481 for (Module::const_named_metadata_iterator
482 I = TheModule->named_metadata_begin(),
483 E = TheModule->named_metadata_end(); I != E; ++I) {
484 const NamedMDNode *NMD = I;
485 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
486 CreateMetadataSlot(NMD->getOperand(i));
487 }
488
489 // Add all the unnamed functions to the table.
490 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
491 I != E; ++I)
492 if (!I->hasName())
493 CreateModuleSlot(I);
494
495 ST_DEBUG("end processModule!\n");
496 }
497
498 // Process the arguments, basic blocks, and instructions of a function.
499 void SlotTracker::processFunction() {
500 ST_DEBUG("begin processFunction!\n");
501 fNext = 0;
502
503 // Add all the function arguments with no names.
504 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
505 AE = TheFunction->arg_end(); AI != AE; ++AI)
506 if (!AI->hasName())
507 CreateFunctionSlot(AI);
508
509 ST_DEBUG("Inserting Instructions:\n");
510
511 SmallVector, 4> MDForInst;
512
513 // Add all of the basic blocks and instructions with no names.
514 for (Function::const_iterator BB = TheFunction->begin(),
515 E = TheFunction->end(); BB != E; ++BB) {
516 if (!BB->hasName())
517 CreateFunctionSlot(BB);
518
519 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
520 ++I) {
521 if (!I->getType()->isVoidTy() && !I->hasName())
522 CreateFunctionSlot(I);
523
524 // Intrinsics can directly use metadata. We allow direct calls to any
525 // llvm.foo function here, because the target may not be linked into the
526 // optimizer.
527 if (const CallInst *CI = dyn_cast(I)) {
528 if (Function *F = CI->getCalledFunction())
529 if (F->getName().startswith("llvm."))
530 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
531 if (MDNode *N = dyn_cast_or_null(I->getOperand(i)))
532 CreateMetadataSlot(N);
533 }
534
535 // Process metadata attached with this instruction.
536 I->getAllMetadata(MDForInst);
537 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
538 CreateMetadataSlot(MDForInst[i].second);
539 MDForInst.clear();
540 }
541 }
542
543 FunctionProcessed = true;
544
545 ST_DEBUG("end processFunction!\n");
546 }
547
548 /// Clean up after incorporating a function. This is the only way to get out of
549 /// the function incorporation state that affects get*Slot/Create*Slot. Function
550 /// incorporation state is indicated by TheFunction != 0.
551 void SlotTracker::purgeFunction() {
552 ST_DEBUG("begin purgeFunction!\n");
553 fMap.clear(); // Simply discard the function level map
554 TheFunction = 0;
555 FunctionProcessed = false;
556 ST_DEBUG("end purgeFunction!\n");
557 }
558
559 /// getGlobalSlot - Get the slot number of a global value.
560 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
561 // Check for uninitialized state and do lazy initialization.
562 initialize();
563
564 // Find the value in the module map
565 ValueMap::iterator MI = mMap.find(V);
566 return MI == mMap.end() ? -1 : (int)MI->second;
567 }
568
569 /// getMetadataSlot - Get the slot number of a MDNode.
570 int SlotTracker::getMetadataSlot(const MDNode *N) {
571 // Check for uninitialized state and do lazy initialization.
572 initialize();
573
574 // Find the MDNode in the module map
575 mdn_iterator MI = mdnMap.find(N);
576 return MI == mdnMap.end() ? -1 : (int)MI->second;
577 }
578
579
580 /// getLocalSlot - Get the slot number for a value that is local to a function.
581 int SlotTracker::getLocalSlot(const Value *V) {
582 assert(!isa(V) && "Can't get a constant or global slot with this!");
583
584 // Check for uninitialized state and do lazy initialization.
585 initialize();
586
587 ValueMap::iterator FI = fMap.find(V);
588 return FI == fMap.end() ? -1 : (int)FI->second;
589 }
590
591
592 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
593 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
594 assert(V && "Can't insert a null Value into SlotTracker!");
595 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
596 assert(!V->hasName() && "Doesn't need a slot!");
597
598 unsigned DestSlot = mNext++;
599 mMap[V] = DestSlot;
600
601 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
602 DestSlot << " [");
603 // G = Global, F = Function, A = Alias, o = other
604 ST_DEBUG((isa(V) ? 'G' :
605 (isa(V) ? 'F' :
606 (isa(V) ? 'A' : 'o'))) << "]\n");
607 }
608
609 /// CreateSlot - Create a new slot for the specified value if it has no name.
610 void SlotTracker::CreateFunctionSlot(const Value *V) {
611 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
612
613 unsigned DestSlot = fNext++;
614 fMap[V] = DestSlot;
615
616 // G = Global, F = Function, o = other
617 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
618 DestSlot << " [o]\n");
619 }
620
621 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
622 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
623 assert(N && "Can't insert a null Value into SlotTracker!");
624
625 // Don't insert if N is a function-local metadata, these are always printed
626 // inline.
627 if (!N->isFunctionLocal()) {
628 mdn_iterator I = mdnMap.find(N);
629 if (I != mdnMap.end())
630 return;
631
632 unsigned DestSlot = mdnNext++;
633 mdnMap[N] = DestSlot;
634 }
635
636 // Recursively add any MDNodes referenced by operands.
637 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
638 if (const MDNode *Op = dyn_cast_or_null(N->getOperand(i)))
639 CreateMetadataSlot(Op);
640 }
641
642 //===----------------------------------------------------------------------===//
643 // AsmWriter Implementation
644 //===----------------------------------------------------------------------===//
645
646 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
647 TypePrinting *TypePrinter,
648 SlotTracker *Machine,
649 const Module *Context);
650
651
652
653 static const char *getPredicateText(unsigned predicate) {
654 const char * pred = "unknown";
655 switch (predicate) {
656 case FCmpInst::FCMP_FALSE: pred = "false"; break;
657 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
658 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
659 case FCmpInst::FCMP_OGE: pred = "oge"; break;
660 case FCmpInst::FCMP_OLT: pred = "olt"; break;
661 case FCmpInst::FCMP_OLE: pred = "ole"; break;
662 case FCmpInst::FCMP_ONE: pred = "one"; break;
663 case FCmpInst::FCMP_ORD: pred = "ord"; break;
664 case FCmpInst::FCMP_UNO: pred = "uno"; break;
665 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
666 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
667 case FCmpInst::FCMP_UGE: pred = "uge"; break;
668 case FCmpInst::FCMP_ULT: pred = "ult"; break;
669 case FCmpInst::FCMP_ULE: pred = "ule"; break;
670 case FCmpInst::FCMP_UNE: pred = "une"; break;
671 case FCmpInst::FCMP_TRUE: pred = "true"; break;
672 case ICmpInst::ICMP_EQ: pred = "eq"; break;
673 case ICmpInst::ICMP_NE: pred = "ne"; break;
674 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
675 case ICmpInst::ICMP_SGE: pred = "sge"; break;
676 case ICmpInst::ICMP_SLT: pred = "slt"; break;
677 case ICmpInst::ICMP_SLE: pred = "sle"; break;
678 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
679 case ICmpInst::ICMP_UGE: pred = "uge"; break;
680 case ICmpInst::ICMP_ULT: pred = "ult"; break;
681 case ICmpInst::ICMP_ULE: pred = "ule"; break;
682 }
683 return pred;
684 }
685
686 static void writeAtomicRMWOperation(raw_ostream &Out,
687 AtomicRMWInst::BinOp Op) {
688 switch (Op) {
689 default: Out << " "; break;
690 case AtomicRMWInst::Xchg: Out << " xchg"; break;
691 case AtomicRMWInst::Add: Out << " add"; break;
692 case AtomicRMWInst::Sub: Out << " sub"; break;
693 case AtomicRMWInst::And: Out << " and"; break;
694 case AtomicRMWInst::Nand: Out << " nand"; break;
695 case AtomicRMWInst::Or: Out << " or"; break;
696 case AtomicRMWInst::Xor: Out << " xor"; break;
697 case AtomicRMWInst::Max: Out << " max"; break;
698 case AtomicRMWInst::Min: Out << " min"; break;
699 case AtomicRMWInst::UMax: Out << " umax"; break;
700 case AtomicRMWInst::UMin: Out << " umin"; break;
701 }
702 }
703
704 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
705 if (const FPMathOperator *FPO = dyn_cast(U)) {
706 // Unsafe algebra implies all the others, no need to write them all out
707 if (FPO->hasUnsafeAlgebra())
708 Out << " fast";
709 else {
710 if (FPO->hasNoNaNs())
711 Out << " nnan";
712 if (FPO->hasNoInfs())
713 Out << " ninf";
714 if (FPO->hasNoSignedZeros())
715 Out << " nsz";
716 if (FPO->hasAllowReciprocal())
717 Out << " arcp";
718 }
719 }
720
721 if (const OverflowingBinaryOperator *OBO =
722 dyn_cast(U)) {
723 if (OBO->hasNoUnsignedWrap())
724 Out << " nuw";
725 if (OBO->hasNoSignedWrap())
726 Out << " nsw";
727 } else if (const PossiblyExactOperator *Div =
728 dyn_cast(U)) {
729 if (Div->isExact())
730 Out << " exact";
731 } else if (const GEPOperator *GEP = dyn_cast(U)) {
732 if (GEP->isInBounds())
733 Out << " inbounds";
734 }
735 }
736
737 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
738 TypePrinting &TypePrinter,
739 SlotTracker *Machine,
740 const Module *Context) {
741 if (const ConstantInt *CI = dyn_cast(CV)) {
742 if (CI->getType()->isIntegerTy(1)) {
743 Out << (CI->getZExtValue() ? "true" : "false");
744 return;
745 }
746 Out << CI->getValue();
747 return;
748 }
749
750 if (const ConstantFP *CFP = dyn_cast(CV)) {
751 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
752 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
753 // We would like to output the FP constant value in exponential notation,
754 // but we cannot do this if doing so will lose precision. Check here to
755 // make sure that we only output it in exponential format if we can parse
756 // the value back and get the same value.
757 //
758 bool ignored;
759 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
760 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
761 bool isInf = CFP->getValueAPF().isInfinity();
762 bool isNaN = CFP->getValueAPF().isNaN();
763 if (!isHalf && !isInf && !isNaN) {
764 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
765 CFP->getValueAPF().convertToFloat();
766 SmallString<128> StrVal;
767 raw_svector_ostream(StrVal) << Val;
768
769 // Check to make sure that the stringized number is not some string like
770 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
771 // that the string matches the "[-+]?[0-9]" regex.
772 //
773 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
774 ((StrVal[0] == '-' || StrVal[0] == '+') &&
775 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
776 // Reparse stringized version!
777 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
778 Out << StrVal.str();
779 return;
780 }
781 }
782 }
783 // Otherwise we could not reparse it to exactly the same value, so we must
784 // output the string in hexadecimal format! Note that loading and storing
785 // floating point types changes the bits of NaNs on some hosts, notably
786 // x86, so we must not use these types.
787 assert(sizeof(double) == sizeof(uint64_t) &&
788 "assuming that double is 64 bits!");
789 char Buffer[40];
790 APFloat apf = CFP->getValueAPF();
791 // Halves and floats are represented in ASCII IR as double, convert.
792 if (!isDouble)
793 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
794 &ignored);
795 Out << "0x" <<
796 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
797 Buffer+40);
798 return;
799 }
800
801 // Either half, or some form of long double.
802 // These appear as a magic letter identifying the type, then a
803 // fixed number of hex digits.
804 Out << "0x";
805 // Bit position, in the current word, of the next nibble to print.
806 int shiftcount;
807
808 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
809 Out << 'K';
810 // api needed to prevent premature destruction
811 APInt api = CFP->getValueAPF().bitcastToAPInt();
812 const uint64_t* p = api.getRawData();
813 uint64_t word = p[1];
814 shiftcount = 12;
815 int width = api.getBitWidth();
816 for (int j=0; j
817 unsigned int nibble = (word>>shiftcount) & 15;
818 if (nibble < 10)
819 Out << (unsigned char)(nibble + '0');
820 else
821 Out << (unsigned char)(nibble - 10 + 'A');
822 if (shiftcount == 0 && j+4 < width) {
823 word = *p;
824 shiftcount = 64;
825 if (width-j-4 < 64)
826 shiftcount = width-j-4;
827 }
828 }
829 return;
830 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
831 shiftcount = 60;
832 Out << 'L';
833 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
834 shiftcount = 60;
835 Out << 'M';
836 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
837 shiftcount = 12;
838 Out << 'H';
839 } else
840 llvm_unreachable("Unsupported floating point type");
841 // api needed to prevent premature destruction
842 APInt api = CFP->getValueAPF().bitcastToAPInt();
843 const uint64_t* p = api.getRawData();
844 uint64_t word = *p;
845 int width = api.getBitWidth();
846 for (int j=0; j
847 unsigned int nibble = (word>>shiftcount) & 15;
848 if (nibble < 10)
849 Out << (unsigned char)(nibble + '0');
850 else
851 Out << (unsigned char)(nibble - 10 + 'A');
852 if (shiftcount == 0 && j+4 < width) {
853 word = *(++p);
854 shiftcount = 64;
855 if (width-j-4 < 64)
856 shiftcount = width-j-4;
857 }
858 }
859 return;
860 }
861
862 if (isa(CV)) {
863 Out << "zeroinitializer";
864 return;
865 }
866
867 if (const BlockAddress *BA = dyn_cast(CV)) {
868 Out << "blockaddress(";
869 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
870 Context);
871 Out << ", ";
872 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
873 Context);
874 Out << ")";
875 return;
876 }
877
878 if (const ConstantArray *CA = dyn_cast(CV)) {
879 Type *ETy = CA->getType()->getElementType();
880 Out << '[';
881 TypePrinter.print(ETy, Out);
882 Out << ' ';
883 WriteAsOperandInternal(Out, CA->getOperand(0),
884 &TypePrinter, Machine,
885 Context);
886 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
887 Out << ", ";
888 TypePrinter.print(ETy, Out);
889 Out << ' ';
890 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
891 Context);
892 }
893 Out << ']';
894 return;
895 }
896
897 if (const ConstantDataArray *CA = dyn_cast(CV)) {
898 // As a special case, print the array as a string if it is an array of
899 // i8 with ConstantInt values.
900 if (CA->isString()) {
901 Out << "c\"";
902 PrintEscapedString(CA->getAsString(), Out);
903 Out << '"';
904 return;
905 }
906
907 Type *ETy = CA->getType()->getElementType();
908 Out << '[';
909 TypePrinter.print(ETy, Out);
910 Out << ' ';
911 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
912 &TypePrinter, Machine,
913 Context);
914 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
915 Out << ", ";
916 TypePrinter.print(ETy, Out);
917 Out << ' ';
918 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
919 Machine, Context);
920 }
921 Out << ']';
922 return;
923 }
924
925
926 if (const ConstantStruct *CS = dyn_cast(CV)) {
927 if (CS->getType()->isPacked())
928 Out << '<';
929 Out << '{';
930 unsigned N = CS->getNumOperands();
931 if (N) {
932 Out << ' ';
933 TypePrinter.print(CS->getOperand(0)->getType(), Out);
934 Out << ' ';
935
936 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
937 Context);
938
939 for (unsigned i = 1; i < N; i++) {
940 Out << ", ";
941 TypePrinter.print(CS->getOperand(i)->getType(), Out);
942 Out << ' ';
943
944 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
945 Context);
946 }
947 Out << ' ';
948 }
949
950 Out << '}';
951 if (CS->getType()->isPacked())
952 Out << '>';
953 return;
954 }
955
956 if (isa(CV) || isa(CV)) {
957 Type *ETy = CV->getType()->getVectorElementType();
958 Out << '<';
959 TypePrinter.print(ETy, Out);
960 Out << ' ';
961 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
962 Machine, Context);
963 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
964 Out << ", ";
965 TypePrinter.print(ETy, Out);
966 Out << ' ';
967 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
968 Machine, Context);
969 }
970 Out << '>';
971 return;
972 }
973
974 if (isa(CV)) {
975 Out << "null";
976 return;
977 }
978
979 if (isa(CV)) {
980 Out << "undef";
981 return;
982 }
983
984 if (const ConstantExpr *CE = dyn_cast(CV)) {
985 Out << CE->getOpcodeName();
986 WriteOptimizationInfo(Out, CE);
987 if (CE->isCompare())
988 Out << ' ' << getPredicateText(CE->getPredicate());
989 Out << " (";
990
991 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
992 TypePrinter.print((*OI)->getType(), Out);
993 Out << ' ';
994 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
995 if (OI+1 != CE->op_end())
996 Out << ", ";
997 }
998
999 if (CE->hasIndices()) {
1000 ArrayRef Indices = CE->getIndices();
1001 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1002 Out << ", " << Indices[i];
1003 }
1004
1005 if (CE->isCast()) {
1006 Out << " to ";
1007 TypePrinter.print(CE->getType(), Out);
1008 }
1009
1010 Out << ')';
1011 return;
1012 }
1013
1014 Out << "";
1015 }
1016
1017 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1018 TypePrinting *TypePrinter,
1019 SlotTracker *Machine,
1020 const Module *Context) {
1021 Out << "!{";
1022 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1023 const Value *V = Node->getOperand(mi);
1024 if (V == 0)
1025 Out << "null";
1026 else {
1027 TypePrinter->print(V->getType(), Out);
1028 Out << ' ';
1029 WriteAsOperandInternal(Out, Node->getOperand(mi),
1030 TypePrinter, Machine, Context);
1031 }
1032 if (mi + 1 != me)
1033 Out << ", ";
1034 }
1035
1036 Out << "}";
1037 }
1038
1039
1040 /// WriteAsOperand - Write the name of the specified value out to the specified
1041 /// ostream. This can be useful when you just want to print int %reg126, not
1042 /// the whole instruction that generated it.
1043 ///
1044 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1045 TypePrinting *TypePrinter,
1046 SlotTracker *Machine,
1047 const Module *Context) {
1048 if (V->hasName()) {
1049 PrintLLVMName(Out, V);
1050 return;
1051 }
1052
1053 const Constant *CV = dyn_cast(V);
1054 if (CV && !isa(CV)) {
1055 assert(TypePrinter && "Constants require TypePrinting!");
1056 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1057 return;
1058 }
1059
1060 if (const InlineAsm *IA = dyn_cast(V)) {
1061 Out << "asm ";
1062 if (IA->hasSideEffects())
1063 Out << "sideeffect ";
1064 if (IA->isAlignStack())
1065 Out << "alignstack ";
1066 // We don't emit the AD_ATT dialect as it's the assumed default.
1067 if (IA->getDialect() == InlineAsm::AD_Intel)
1068 Out << "inteldialect ";
1069 Out << '"';
1070 PrintEscapedString(IA->getAsmString(), Out);
1071 Out << "\", \"";
1072 PrintEscapedString(IA->getConstraintString(), Out);
1073 Out << '"';
1074 return;
1075 }
1076
1077 if (const MDNode *N = dyn_cast(V)) {
1078 if (N->isFunctionLocal()) {
1079 // Print metadata inline, not via slot reference number.
1080 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1081 return;
1082 }
1083
1084 if (!Machine) {
1085 if (N->isFunctionLocal())
1086 Machine = new SlotTracker(N->getFunction());
1087 else
1088 Machine = new SlotTracker(Context);
1089 }
1090 int Slot = Machine->getMetadataSlot(N);
1091 if (Slot == -1)
1092 Out << "";
1093 else
1094 Out << '!' << Slot;
1095 return;
1096 }
1097
1098 if (const MDString *MDS = dyn_cast(V)) {
1099 Out << "!\"";
1100 PrintEscapedString(MDS->getString(), Out);
1101 Out << '"';
1102 return;
1103 }
1104
1105 if (V->getValueID() == Value::PseudoSourceValueVal ||
1106 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1107 V->print(Out);
1108 return;
1109 }
1110
1111 char Prefix = '%';
1112 int Slot;
1113 // If we have a SlotTracker, use it.
1114 if (Machine) {
1115 if (const GlobalValue *GV = dyn_cast(V)) {
1116 Slot = Machine->getGlobalSlot(GV);
1117 Prefix = '@';
1118 } else {
1119 Slot = Machine->getLocalSlot(V);
1120
1121 // If the local value didn't succeed, then we may be referring to a value
1122 // from a different function. Translate it, as this can happen when using
1123 // address of blocks.
1124 if (Slot == -1)
1125 if ((Machine = createSlotTracker(V))) {
1126 Slot = Machine->getLocalSlot(V);
1127 delete Machine;
1128 }
1129 }
1130 } else if ((Machine = createSlotTracker(V))) {
1131 // Otherwise, create one to get the # and then destroy it.
1132 if (const GlobalValue *GV = dyn_cast(V)) {
1133 Slot = Machine->getGlobalSlot(GV);
1134 Prefix = '@';
1135 } else {
1136 Slot = Machine->getLocalSlot(V);
1137 }
1138 delete Machine;
1139 Machine = 0;
1140 } else {
1141 Slot = -1;
1142 }
1143
1144 if (Slot != -1)
1145 Out << Prefix << Slot;
1146 else
1147 Out << "";
1148 }
1149
1150 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1151 bool PrintType, const Module *Context) {
1152
1153 // Fast path: Don't construct and populate a TypePrinting object if we
1154 // won't be needing any types printed.
1155 if (!PrintType &&
1156 ((!isa(V) && !isa(V)) ||
1157 V->hasName() || isa(V))) {
1158 WriteAsOperandInternal(Out, V, 0, 0, Context);
1159 return;
1160 }
1161
1162 if (Context == 0) Context = getModuleFromVal(V);
1163
1164 TypePrinting TypePrinter;
1165 if (Context)
1166 TypePrinter.incorporateTypes(*Context);
1167 if (PrintType) {
1168 TypePrinter.print(V->getType(), Out);
1169 Out << ' ';
1170 }
1171
1172 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1173 }
1174
1175 namespace {
1176
1177 class AssemblyWriter {
1178 formatted_raw_ostream &Out;
1179 SlotTracker &Machine;
1180 const Module *TheModule;
1181 TypePrinting TypePrinter;
1182 AssemblyAnnotationWriter *AnnotationWriter;
1183
1184 public:
1185 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1186 const Module *M,
1187 AssemblyAnnotationWriter *AAW)
1188 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1189 if (M)
1190 TypePrinter.incorporateTypes(*M);
1191 }
1192
1193 void printMDNodeBody(const MDNode *MD);
1194 void printNamedMDNode(const NamedMDNode *NMD);
1195
1196 void printModule(const Module *M);
1197
1198 void writeOperand(const Value *Op, bool PrintType);
1199 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
1200 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1201
1202 void writeAllMDNodes();
1203
1204 void printTypeIdentities();
1205 void printGlobal(const GlobalVariable *GV);
1206 void printAlias(const GlobalAlias *GV);
1207 void printFunction(const Function *F);
1208 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
1209 void printBasicBlock(const BasicBlock *BB);
1210 void printInstruction(const Instruction &I);
1211
1212 private:
1213 // printInfoComment - Print a little comment after the instruction indicating
1214 // which slot it occupies.
1215 void printInfoComment(const Value &V);
1216 };
1217 } // end of anonymous namespace
1218
1219 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1220 if (Operand == 0) {
1221 Out << "";
1222 return;
1223 }
1224 if (PrintType) {
1225 TypePrinter.print(Operand->getType(), Out);
1226 Out << ' ';
1227 }
1228 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1229 }
1230
1231 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1232 SynchronizationScope SynchScope) {
1233 if (Ordering == NotAtomic)
1234 return;
1235
1236 switch (SynchScope) {
1237 case SingleThread: Out << " singlethread"; break;
1238 case CrossThread: break;
1239 }
1240
1241 switch (Ordering) {
1242 default: Out << " "; break;
1243 case Unordered: Out << " unordered"; break;
1244 case Monotonic: Out << " monotonic"; break;
1245 case Acquire: Out << " acquire"; break;
1246 case Release: Out << " release"; break;
1247 case AcquireRelease: Out << " acq_rel"; break;
1248 case SequentiallyConsistent: Out << " seq_cst"; break;
1249 }
1250 }
1251
1252 void AssemblyWriter::writeParamOperand(const Value *Operand,
1253 AttributeSet Attrs, unsigned Idx) {
1254 if (Operand == 0) {
1255 Out << "";
1256 return;
1257 }
1258
1259 // Print the type
1260 TypePrinter.print(Operand->getType(), Out);
1261 // Print parameter attributes list
1262 if (Attrs.hasAttributes(Idx))
1263 Out << ' ' << Attrs.getAsString(Idx);
1264 Out << ' ';
1265 // Print the operand
1266 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1267 }
1268
1269 void AssemblyWriter::printModule(const Module *M) {
1270 if (!M->getModuleIdentifier().empty() &&
1271 // Don't print the ID if it will start a new line (which would
1272 // require a comment char before it).
1273 M->getModuleIdentifier().find('\n') == std::string::npos)
1274 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1275
1276 if (!M->getDataLayout().empty())
1277 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1278 if (!M->getTargetTriple().empty())
1279 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1280
1281 if (!M->getModuleInlineAsm().empty()) {
1282 // Split the string into lines, to make it easier to read the .ll file.
1283 std::string Asm = M->getModuleInlineAsm();
1284 size_t CurPos = 0;
1285 size_t NewLine = Asm.find_first_of('\n', CurPos);
1286 Out << '\n';
1287 while (NewLine != std::string::npos) {
1288 // We found a newline, print the portion of the asm string from the
1289 // last newline up to this newline.
1290 Out << "module asm \"";
1291 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1292 Out);
1293 Out << "\"\n";
1294 CurPos = NewLine+1;
1295 NewLine = Asm.find_first_of('\n', CurPos);
1296 }
1297 std::string rest(Asm.begin()+CurPos, Asm.end());
1298 if (!rest.empty()) {
1299 Out << "module asm \"";
1300 PrintEscapedString(rest, Out);
1301 Out << "\"\n";
1302 }
1303 }
1304
1305 printTypeIdentities();
1306
1307 // Output all globals.
1308 if (!M->global_empty()) Out << '\n';
1309 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1310 I != E; ++I) {
1311 printGlobal(I); Out << '\n';
1312 }
1313
1314 // Output all aliases.
1315 if (!M->alias_empty()) Out << "\n";
1316 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1317 I != E; ++I)
1318 printAlias(I);
1319
1320 // Output all of the functions.
1321 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1322 printFunction(I);
1323
1324 // Output named metadata.
1325 if (!M->named_metadata_empty()) Out << '\n';
1326
1327 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1328 E = M->named_metadata_end(); I != E; ++I)
1329 printNamedMDNode(I);
1330
1331 // Output metadata.
1332 if (!Machine.mdn_empty()) {
1333 Out << '\n';
1334 writeAllMDNodes();
1335 }
1336 }
1337
1338 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1339 Out << '!';
1340 StringRef Name = NMD->getName();
1341 if (Name.empty()) {
1342 Out << " ";
1343 } else {
1344 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1345 Name[0] == '.' || Name[0] == '_')
1346 Out << Name[0];
1347 else
1348 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1349 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1350 unsigned char C = Name[i];
1351 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1352 Out << C;
1353 else
1354 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1355 }
1356 }
1357 Out << " = !{";
1358 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1359 if (i) Out << ", ";
1360 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1361 if (Slot == -1)
1362 Out << "";
1363 else
1364 Out << '!' << Slot;
1365 }
1366 Out << "}\n";
1367 }
1368
1369
1370 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1371 formatted_raw_ostream &Out) {
1372 switch (LT) {
1373 case GlobalValue::ExternalLinkage: break;
1374 case GlobalValue::PrivateLinkage: Out << "private "; break;
1375 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1376 case GlobalValue::LinkerPrivateWeakLinkage:
1377 Out << "linker_private_weak ";
1378 break;
1379 case GlobalValue::InternalLinkage: Out << "internal "; break;
1380 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1381 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1382 case GlobalValue::LinkOnceODRAutoHideLinkage:
1383 Out << "linkonce_odr_auto_hide ";
1384 break;
1385 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1386 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1387 case GlobalValue::CommonLinkage: Out << "common "; break;
1388 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1389 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1390 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1391 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1392 case GlobalValue::AvailableExternallyLinkage:
1393 Out << "available_externally ";
1394 break;
1395 }
1396 }
1397
1398
1399 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1400 formatted_raw_ostream &Out) {
1401 switch (Vis) {
1402 case GlobalValue::DefaultVisibility: break;
1403 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1404 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1405 }
1406 }
1407
1408 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1409 formatted_raw_ostream &Out) {
1410 switch (TLM) {
1411 case GlobalVariable::NotThreadLocal:
1412 break;
1413 case GlobalVariable::GeneralDynamicTLSModel:
1414 Out << "thread_local ";
1415 break;
1416 case GlobalVariable::LocalDynamicTLSModel:
1417 Out << "thread_local(localdynamic) ";
1418 break;
1419 case GlobalVariable::InitialExecTLSModel:
1420 Out << "thread_local(initialexec) ";
1421 break;
1422 case GlobalVariable::LocalExecTLSModel:
1423 Out << "thread_local(localexec) ";
1424 break;
1425 }
1426 }
1427
1428 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1429 if (GV->isMaterializable())
1430 Out << "; Materializable\n";
1431
1432 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1433 Out << " = ";
1434
1435 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1436 Out << "external ";
1437
1438 PrintLinkage(GV->getLinkage(), Out);
1439 PrintVisibility(GV->getVisibility(), Out);
1440 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1441
1442 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1443 Out << "addrspace(" << AddressSpace << ") ";
1444 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1445 Out << (GV->isConstant() ? "constant " : "global ");
1446 TypePrinter.print(GV->getType()->getElementType(), Out);
1447
1448 if (GV->hasInitializer()) {
1449 Out << ' ';
1450 writeOperand(GV->getInitializer(), false);
1451 }
1452
1453 if (GV->hasSection()) {
1454 Out << ", section \"";
1455 PrintEscapedString(GV->getSection(), Out);
1456 Out << '"';
1457 }
1458 if (GV->getAlignment())
1459 Out << ", align " << GV->getAlignment();
1460
1461 printInfoComment(*GV);
1462 }
1463
1464 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1465 if (GA->isMaterializable())
1466 Out << "; Materializable\n";
1467
1468 // Don't crash when dumping partially built GA
1469 if (!GA->hasName())
1470 Out << "<> = ";
1471 else {
1472 PrintLLVMName(Out, GA);
1473 Out << " = ";
1474 }
1475 PrintVisibility(GA->getVisibility(), Out);
1476
1477 Out << "alias ";
1478
1479 PrintLinkage(GA->getLinkage(), Out);
1480
1481 const Constant *Aliasee = GA->getAliasee();
1482
1483 if (Aliasee == 0) {
1484 TypePrinter.print(GA->getType(), Out);
1485 Out << " <>";
1486 } else {
1487 writeOperand(Aliasee, !isa(Aliasee));
1488 }
1489
1490 printInfoComment(*GA);
1491 Out << '\n';
1492 }
1493
1494 void AssemblyWriter::printTypeIdentities() {
1495 if (TypePrinter.NumberedTypes.empty() &&
1496 TypePrinter.NamedTypes.empty())
1497 return;
1498
1499 Out << '\n';
1500
1501 // We know all the numbers that each type is used and we know that it is a
1502 // dense assignment. Convert the map to an index table.
1503 std::vector NumberedTypes(TypePrinter.NumberedTypes.size());
1504 for (DenseMap::iterator I =
1505 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1506 I != E; ++I) {
1507 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1508 NumberedTypes[I->second] = I->first;
1509 }
1510
1511 // Emit all numbered types.
1512 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1513 Out << '%' << i << " = type ";
1514
1515 // Make sure we print out at least one level of the type structure, so
1516 // that we do not get %2 = type %2
1517 TypePrinter.printStructBody(NumberedTypes[i], Out);
1518 Out << '\n';
1519 }
1520
1521 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1522 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1523 Out << " = type ";
1524
1525 // Make sure we print out at least one level of the type structure, so
1526 // that we do not get %FILE = type %FILE
1527 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1528 Out << '\n';
1529 }
1530 }
1531
1532 /// printFunction - Print all aspects of a function.
1533 ///
1534 void AssemblyWriter::printFunction(const Function *F) {
1535 // Print out the return type and name.
1536 Out << '\n';
1537
1538 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1539
1540 if (F->isMaterializable())
1541 Out << "; Materializable\n";
1542
1543 if (F->isDeclaration())
1544 Out << "declare ";
1545 else
1546 Out << "define ";
1547
1548 PrintLinkage(F->getLinkage(), Out);
1549 PrintVisibility(F->getVisibility(), Out);
1550
1551 // Print the calling convention.
1552 if (F->getCallingConv() != CallingConv::C) {
1553 PrintCallingConv(F->getCallingConv(), Out);
1554 Out << " ";
1555 }
1556
1557 FunctionType *FT = F->getFunctionType();
1558 const AttributeSet &Attrs = F->getAttributes();
1559 Attribute RetAttrs = Attrs.getRetAttributes();
1560 if (RetAttrs.hasAttributes())
1561 Out << Attrs.getRetAttributes().getAsString() << ' ';
1562 TypePrinter.print(F->getReturnType(), Out);
1563 Out << ' ';
1564 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1565 Out << '(';
1566 Machine.incorporateFunction(F);
1567
1568 // Loop over the arguments, printing them...
1569
1570 unsigned Idx = 1;
1571 if (!F->isDeclaration()) {
1572 // If this isn't a declaration, print the argument names as well.
1573 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1574 I != E; ++I) {
1575 // Insert commas as we go... the first arg doesn't get a comma
1576 if (I != F->arg_begin()) Out << ", ";
1577 printArgument(I, Attrs, Idx);
1578 Idx++;
1579 }
1580 } else {
1581 // Otherwise, print the types from the function type.
1582 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1583 // Insert commas as we go... the first arg doesn't get a comma
1584 if (i) Out << ", ";
1585
1586 // Output type...
1587 TypePrinter.print(FT->getParamType(i), Out);
1588
1589 if (Attrs.hasAttributes(i+1))
1590 Out << ' ' << Attrs.getAsString(i+1);
1591 }
1592 }
1593
1594 // Finish printing arguments...
1595 if (FT->isVarArg()) {
1596 if (FT->getNumParams()) Out << ", ";
1597 Out << "..."; // Output varargs portion of signature!
1598 }
1599 Out << ')';
1600 if (F->hasUnnamedAddr())
1601 Out << " unnamed_addr";
1602 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1603 Out << ' ' << Attrs.getAsString(AttributeSet::FunctionIndex);
1604 if (F->hasSection()) {
1605 Out << " section \"";
1606 PrintEscapedString(F->getSection(), Out);
1607 Out << '"';
1608 }
1609 if (F->getAlignment())
1610 Out << " align " << F->getAlignment();
1611 if (F->hasGC())
1612 Out << " gc \"" << F->getGC() << '"';
1613 if (F->isDeclaration()) {
1614 Out << '\n';
1615 } else {
1616 Out << " {";
1617 // Output all of the function's basic blocks.
1618 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1619 printBasicBlock(I);
1620
1621 Out << "}\n";
1622 }
1623
1624 Machine.purgeFunction();
1625 }
1626
1627 /// printArgument - This member is called for every argument that is passed into
1628 /// the function. Simply print it out
1629 ///
1630 void AssemblyWriter::printArgument(const Argument *Arg,
1631 AttributeSet Attrs, unsigned Idx) {
1632 // Output type...
1633 TypePrinter.print(Arg->getType(), Out);
1634
1635 // Output parameter attributes list
1636 if (Attrs.hasAttributes(Idx))
1637 Out << ' ' << Attrs.getAsString(Idx);
1638
1639 // Output name, if available...
1640 if (Arg->hasName()) {
1641 Out << ' ';
1642 PrintLLVMName(Out, Arg);
1643 }
1644 }
1645
1646 /// printBasicBlock - This member is called for each basic block in a method.
1647 ///
1648 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1649 if (BB->hasName()) { // Print out the label if it exists...
1650 Out << "\n";
1651 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1652 Out << ':';
1653 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1654 Out << "\n;
1655 int Slot = Machine.getLocalSlot(BB);
1656 if (Slot != -1)
1657 Out << Slot;
1658 else
1659 Out << "";
1660 }
1661
1662 if (BB->getParent() == 0) {
1663 Out.PadToColumn(50);
1664 Out << "; Error: Block without parent!";
1665 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1666 // Output predecessors for the block.
1667 Out.PadToColumn(50);
1668 Out << ";";
1669 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1670
1671 if (PI == PE) {
1672 Out << " No predecessors!";
1673 } else {
1674 Out << " preds = ";
1675 writeOperand(*PI, false);
1676 for (++PI; PI != PE; ++PI) {
1677 Out << ", ";
1678 writeOperand(*PI, false);
1679 }
1680 }
1681 }
1682
1683 Out << "\n";
1684
1685 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1686
1687 // Output all of the instructions in the basic block...
1688 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1689 printInstruction(*I);
1690 Out << '\n';
1691 }
1692
1693 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1694 }
1695
1696 /// printInfoComment - Print a little comment after the instruction indicating
1697 /// which slot it occupies.
1698 ///
1699 void AssemblyWriter::printInfoComment(const Value &V) {
1700 if (AnnotationWriter) {
1701 AnnotationWriter->printInfoComment(V, Out);
1702 return;
1703 }
1704 }
1705
1706 // This member is called for each Instruction in a function..
1707 void AssemblyWriter::printInstruction(const Instruction &I) {
1708 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1709
1710 // Print out indentation for an instruction.
1711 Out << " ";
1712
1713 // Print out name if it exists...
1714 if (I.hasName()) {
1715 PrintLLVMName(Out, &I);
1716 Out << " = ";
1717 } else if (!I.getType()->isVoidTy()) {
1718 // Print out the def slot taken.
1719 int SlotNum = Machine.getLocalSlot(&I);
1720 if (SlotNum == -1)
1721 Out << " = ";
1722 else
1723 Out << '%' << SlotNum << " = ";
1724 }
1725
1726 if (isa(I) && cast(I).isTailCall())
1727 Out << "tail ";
1728
1729 // Print out the opcode...
1730 Out << I.getOpcodeName();
1731
1732 // If this is an atomic load or store, print out the atomic marker.
1733 if ((isa(I) && cast(I).isAtomic()) ||
1734 (isa(I) && cast(I).isAtomic()))
1735 Out << " atomic";
1736
1737 // If this is a volatile operation, print out the volatile marker.
1738 if ((isa(I) && cast(I).isVolatile()) ||
1739 (isa(I) && cast(I).isVolatile()) ||
1740 (isa(I) && cast(I).isVolatile()) ||
1741 (isa(I) && cast(I).isVolatile()))
1742 Out << " volatile";
1743
1744 // Print out optimization information.
1745 WriteOptimizationInfo(Out, &I);
1746
1747 // Print out the compare instruction predicates
1748 if (const CmpInst *CI = dyn_cast(&I))
1749 Out << ' ' << getPredicateText(CI->getPredicate());
1750
1751 // Print out the atomicrmw operation
1752 if (const AtomicRMWInst *RMWI = dyn_cast(&I))
1753 writeAtomicRMWOperation(Out, RMWI->getOperation());
1754
1755 // Print out the type of the operands...
1756 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1757
1758 // Special case conditional branches to swizzle the condition out to the front
1759 if (isa(I) && cast(I).isConditional()) {
1760 BranchInst &BI(cast(I));
1761 Out << ' ';
1762 writeOperand(BI.getCondition(), true);
1763 Out << ", ";
1764 writeOperand(BI.getSuccessor(0), true);
1765 Out << ", ";
1766 writeOperand(BI.getSuccessor(1), true);
1767
1768 } else if (isa(I)) {
1769 SwitchInst& SI(cast(I));
1770 // Special case switch instruction to get formatting nice and correct.
1771 Out << ' ';
1772 writeOperand(SI.getCondition(), true);
1773 Out << ", ";
1774 writeOperand(SI.getDefaultDest(), true);
1775 Out << " [";
1776 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1777 i != e; ++i) {
1778 Out << "\n ";
1779 writeOperand(i.getCaseValue(), true);
1780 Out << ", ";
1781 writeOperand(i.getCaseSuccessor(), true);
1782 }
1783 Out << "\n ]";
1784 } else if (isa(I)) {
1785 // Special case indirectbr instruction to get formatting nice and correct.
1786 Out << ' ';
1787 writeOperand(Operand, true);
1788 Out << ", [";
1789
1790 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1791 if (i != 1)
1792 Out << ", ";
1793 writeOperand(I.getOperand(i), true);
1794 }
1795 Out << ']';
1796 } else if (const PHINode *PN = dyn_cast(&I)) {
1797 Out << ' ';
1798 TypePrinter.print(I.getType(), Out);
1799 Out << ' ';
1800
1801 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1802 if (op) Out << ", ";
1803 Out << "[ ";
1804 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1805 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1806 }
1807 } else if (const ExtractValueInst *EVI = dyn_cast(&I)) {
1808 Out << ' ';
1809 writeOperand(I.getOperand(0), true);
1810 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1811 Out << ", " << *i;
1812 } else if (const InsertValueInst *IVI = dyn_cast(&I)) {
1813 Out << ' ';
1814 writeOperand(I.getOperand(0), true); Out << ", ";
1815 writeOperand(I.getOperand(1), true);
1816 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1817 Out << ", " << *i;
1818 } else if (const LandingPadInst *LPI = dyn_cast(&I)) {
1819 Out << ' ';
1820 TypePrinter.print(I.getType(), Out);
1821 Out << " personality ";
1822 writeOperand(I.getOperand(0), true); Out << '\n';
1823
1824 if (LPI->isCleanup())
1825 Out << " cleanup";
1826
1827 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1828 if (i != 0 || LPI->isCleanup()) Out << "\n";
1829 if (LPI->isCatch(i))
1830 Out << " catch ";
1831 else
1832 Out << " filter ";
1833
1834 writeOperand(LPI->getClause(i), true);
1835 }
1836 } else if (isa(I) && !Operand) {
1837 Out << " void";
1838 } else if (const CallInst *CI = dyn_cast(&I)) {
1839 // Print the calling convention being used.
1840 if (CI->getCallingConv() != CallingConv::C) {
1841 Out << " ";
1842 PrintCallingConv(CI->getCallingConv(), Out);
1843 }
1844
1845 Operand = CI->getCalledValue();
1846 PointerType *PTy = cast(Operand->getType());
1847 FunctionType *FTy = cast(PTy->getElementType());
1848 Type *RetTy = FTy->getReturnType();
1849 const AttributeSet &PAL = CI->getAttributes();
1850
1851 if (PAL.getRetAttributes().hasAttributes())
1852 Out << ' ' << PAL.getRetAttributes().getAsString();
1853
1854 // If possible, print out the short form of the call instruction. We can
1855 // only do this if the first argument is a pointer to a nonvararg function,
1856 // and if the return type is not a pointer to a function.
1857 //
1858 Out << ' ';
1859 if (!FTy->isVarArg() &&
1860 (!RetTy->isPointerTy() ||
1861 !cast(RetTy)->getElementType()->isFunctionTy())) {
1862 TypePrinter.print(RetTy, Out);
1863 Out << ' ';
1864 writeOperand(Operand, false);
1865 } else {
1866 writeOperand(Operand, true);
1867 }
1868 Out << '(';
1869 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1870 if (op > 0)
1871 Out << ", ";
1872 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
1873 }
1874 Out << ')';
1875 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1876 Out << ' ' << PAL.getAsString(AttributeSet::FunctionIndex);
1877 } else if (const InvokeInst *II = dyn_cast(&I)) {
1878 Operand = II->getCalledValue();
1879 PointerType *PTy = cast(Operand->getType());
1880 FunctionType *FTy = cast(PTy->getElementType());
1881 Type *RetTy = FTy->getReturnType();
1882 const AttributeSet &PAL = II->getAttributes();
1883
1884 // Print the calling convention being used.
1885 if (II->getCallingConv() != CallingConv::C) {
1886 Out << " ";
1887 PrintCallingConv(II->getCallingConv(), Out);
1888 }
1889
1890 if (PAL.getRetAttributes().hasAttributes())
1891 Out << ' ' << PAL.getRetAttributes().getAsString();
1892
1893 // If possible, print out the short form of the invoke instruction. We can
1894 // only do this if the first argument is a pointer to a nonvararg function,
1895 // and if the return type is not a pointer to a function.
1896 //
1897 Out << ' ';
1898 if (!FTy->isVarArg() &&
1899 (!RetTy->isPointerTy() ||
1900 !cast(RetTy)->getElementType()->isFunctionTy())) {
1901 TypePrinter.print(RetTy, Out);
1902 Out << ' ';
1903 writeOperand(Operand, false);
1904 } else {
1905 writeOperand(Operand, true);
1906 }
1907 Out << '(';
1908 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1909 if (op)
1910 Out << ", ";
1911 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
1912 }
1913
1914 Out << ')';
1915 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1916 Out << ' ' << PAL.getAsString(AttributeSet::FunctionIndex);
1917
1918 Out << "\n to ";
1919 writeOperand(II->getNormalDest(), true);
1920 Out << " unwind ";
1921 writeOperand(II->getUnwindDest(), true);
1922
1923 } else if (const AllocaInst *AI = dyn_cast(&I)) {
1924 Out << ' ';
1925 TypePrinter.print(AI->getType()->getElementType(), Out);
1926 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1927 Out << ", ";
1928 writeOperand(AI->getArraySize(), true);
1929 }
1930 if (AI->getAlignment()) {
1931 Out << ", align " << AI->getAlignment();
1932 }
1933 } else if (isa(I)) {
1934 if (Operand) {
1935 Out << ' ';
1936 writeOperand(Operand, true); // Work with broken code
1937 }
1938 Out << " to ";
1939 TypePrinter.print(I.getType(), Out);
1940 } else if (isa(I)) {
1941 if (Operand) {
1942 Out << ' ';
1943 writeOperand(Operand, true); // Work with broken code
1944 }
1945 Out << ", ";
1946 TypePrinter.print(I.getType(), Out);
1947 } else if (Operand) { // Print the normal way.
1948
1949 // PrintAllTypes - Instructions who have operands of all the same type
1950 // omit the type from all but the first operand. If the instruction has
1951 // different type operands (for example br), then they are all printed.
1952 bool PrintAllTypes = false;
1953 Type *TheType = Operand->getType();
1954
1955 // Select, Store and ShuffleVector always print all types.
1956 if (isa(I) || isa(I) || isa(I)
1957 || isa(I)) {
1958 PrintAllTypes = true;
1959 } else {
1960 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1961 Operand = I.getOperand(i);
1962 // note that Operand shouldn't be null, but the test helps make dump()
1963 // more tolerant of malformed IR
1964 if (Operand && Operand->getType() != TheType) {
1965 PrintAllTypes = true; // We have differing types! Print them all!
1966 break;
1967 }
1968 }
1969 }
1970
1971 if (!PrintAllTypes) {
1972 Out << ' ';
1973 TypePrinter.print(TheType, Out);
1974 }
1975
1976 Out << ' ';
1977 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1978 if (i) Out << ", ";
1979 writeOperand(I.getOperand(i), PrintAllTypes);
1980 }
1981 }
1982
1983 // Print atomic ordering/alignment for memory operations
1984 if (const LoadInst *LI = dyn_cast(&I)) {
1985 if (LI->isAtomic())
1986 writeAtomic(LI->getOrdering(), LI->getSynchScope());
1987 if (LI->getAlignment())
1988 Out << ", align " << LI->getAlignment();
1989 } else if (const StoreInst *SI = dyn_cast(&I)) {
1990 if (SI->isAtomic())
1991 writeAtomic(SI->getOrdering(), SI->getSynchScope());
1992 if (SI->getAlignment())
1993 Out << ", align " << SI->getAlignment();
1994 } else if (const AtomicCmpXchgInst *CXI = dyn_cast(&I)) {
1995 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
1996 } else if (const AtomicRMWInst *RMWI = dyn_cast(&I)) {
1997 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
1998 } else if (const FenceInst *FI = dyn_cast(&I)) {
1999 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2000 }
2001
2002 // Print Metadata info.
2003 SmallVector, 4> InstMD;
2004 I.getAllMetadata(InstMD);
2005 if (!InstMD.empty()) {
2006 SmallVector MDNames;
2007 I.getType()->getContext().getMDKindNames(MDNames);
2008 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2009 unsigned Kind = InstMD[i].first;
2010 if (Kind < MDNames.size()) {
2011 Out << ", !" << MDNames[Kind];
2012 } else {
2013 Out << ", !";
2014 }
2015 Out << ' ';
2016 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2017 TheModule);
2018 }
2019 }
2020 printInfoComment(I);
2021 }
2022
2023 static void WriteMDNodeComment(const MDNode *Node,
2024 formatted_raw_ostream &Out) {
2025 if (Node->getNumOperands() < 1)
2026 return;
2027
2028 Value *Op = Node->getOperand(0);
2029 if (!Op || !isa(Op) || cast(Op)->getBitWidth() < 32)
2030 return;
2031
2032 DIDescriptor Desc(Node);
2033 if (Desc.getVersion() < LLVMDebugVersion11)
2034 return;
2035
2036 unsigned Tag = Desc.getTag();
2037 Out.PadToColumn(50);
2038 if (dwarf::TagString(Tag)) {
2039 Out << "; ";
2040 Desc.print(Out);
2041 } else if (Tag == dwarf::DW_TAG_user_base) {
2042 Out << "; [ DW_TAG_user_base ]";
2043 }
2044 }
2045
2046 void AssemblyWriter::writeAllMDNodes() {
2047 SmallVector Nodes;
2048 Nodes.resize(Machine.mdn_size());
2049 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2050 I != E; ++I)
2051 Nodes[I->second] = cast(I->first);
2052
2053 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2054 Out << '!' << i << " = metadata ";
2055 printMDNodeBody(Nodes[i]);
2056 }
2057 }
2058
2059 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2060 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2061 WriteMDNodeComment(Node, Out);
2062 Out << "\n";
2063 }
2064
2065 //===----------------------------------------------------------------------===//
2066 // External Interface declarations
2067 //===----------------------------------------------------------------------===//
2068
2069 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2070 SlotTracker SlotTable(this);
2071 formatted_raw_ostream OS(ROS);
2072 AssemblyWriter W(OS, SlotTable, this, AAW);
2073 W.printModule(this);
2074 }
2075
2076 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2077 SlotTracker SlotTable(getParent());
2078 formatted_raw_ostream OS(ROS);
2079 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2080 W.printNamedMDNode(this);
2081 }
2082
2083 void Type::print(raw_ostream &OS) const {
2084 if (this == 0) {
2085 OS << "";
2086 return;
2087 }
2088 TypePrinting TP;
2089 TP.print(const_cast(this), OS);
2090
2091 // If the type is a named struct type, print the body as well.
2092 if (StructType *STy = dyn_cast(const_cast(this)))
2093 if (!STy->isLiteral()) {
2094 OS << " = type ";
2095 TP.printStructBody(STy, OS);
2096 }
2097 }
2098
2099 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2100 if (this == 0) {
2101 ROS << "printing a value\n";
2102 return;
2103 }
2104 formatted_raw_ostream OS(ROS);
2105 if (const Instruction *I = dyn_cast(this)) {
2106 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2107 SlotTracker SlotTable(F);
2108 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2109 W.printInstruction(*I);
2110 } else if (const BasicBlock *BB = dyn_cast(this)) {
2111 SlotTracker SlotTable(BB->getParent());
2112 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2113 W.printBasicBlock(BB);
2114 } else if (const GlobalValue *GV = dyn_cast(this)) {
2115 SlotTracker SlotTable(GV->getParent());
2116 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2117 if (const GlobalVariable *V = dyn_cast(GV))
2118 W.printGlobal(V);
2119 else if (const Function *F = dyn_cast(GV))
2120 W.printFunction(F);
2121 else
2122 W.printAlias(cast(GV));
2123 } else if (const MDNode *N = dyn_cast(this)) {
2124 const Function *F = N->getFunction();
2125 SlotTracker SlotTable(F);
2126 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2127 W.printMDNodeBody(N);
2128 } else if (const Constant *C = dyn_cast(this)) {
2129 TypePrinting TypePrinter;
2130 TypePrinter.print(C->getType(), OS);
2131 OS << ' ';
2132 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2133 } else if (isa(this) || isa(this) ||
2134 isa(this)) {
2135 WriteAsOperand(OS, this, true, 0);
2136 } else {
2137 // Otherwise we don't know what it is. Call the virtual function to
2138 // allow a subclass to print itself.
2139 printCustom(OS);
2140 }
2141 }
2142
2143 // Value::printCustom - subclasses should override this to implement printing.
2144 void Value::printCustom(raw_ostream &OS) const {
2145 llvm_unreachable("Unknown value to print out!");
2146 }
2147
2148 // Value::dump - allow easy printing of Values from the debugger.
2149 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2150
2151 // Type::dump - allow easy printing of Types from the debugger.
2152 void Type::dump() const { print(dbgs()); }
2153
2154 // Module::dump() - Allow printing of Modules from the debugger.
2155 void Module::dump() const { print(dbgs(), 0); }
2156
2157 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2158 void NamedMDNode::dump() const { print(dbgs(), 0); }
0 //===-- AttributeImpl.h - Attribute Internals -------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// \brief This file defines various helper methods and classes used by
11 /// LLVMContextImpl for creating and managing attributes.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ATTRIBUTESIMPL_H
16 #define LLVM_ATTRIBUTESIMPL_H
17
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/Attributes.h"
20
21 namespace llvm {
22
23 class Constant;
24 class LLVMContext;
25
26 //===----------------------------------------------------------------------===//
27 /// \class
28 /// \brief This class represents a single, uniqued attribute. That attribute
29 /// could be a single enum, a tuple, or a string.
30 class AttributeImpl : public FoldingSetNode {
31 Constant *Data;
32 SmallVector Vals;
33 public:
34 explicit AttributeImpl(LLVMContext &C, uint64_t data);
35 explicit AttributeImpl(LLVMContext &C, Attribute::AttrKind data);
36 AttributeImpl(LLVMContext &C, Attribute::AttrKind data,
37 ArrayRef values);
38 AttributeImpl(LLVMContext &C, StringRef data);
39
40 ArrayRef getValues() const {
41 return Vals;
42 }
43
44 bool contains(Attribute::AttrKind Kind) const;
45 bool contains(StringRef Kind) const;
46
47 bool hasAttribute(uint64_t A) const;
48
49 bool hasAttributes() const;
50 bool hasAttributes(const Attribute &A) const;
51
52 uint64_t getAlignment() const;
53 uint64_t getStackAlignment() const;
54
55 bool operator==(Attribute::AttrKind Kind) const {
56 return contains(Kind);
57 }
58 bool operator!=(Attribute::AttrKind Kind) const {
59 return !contains(Kind);
60 }
61
62 bool operator==(StringRef Kind) const {
63 return contains(Kind);
64 }
65 bool operator!=(StringRef Kind) const {
66 return !contains(Kind);
67 }
68
69 uint64_t getBitMask() const; // FIXME: Remove.
70
71 static uint64_t getAttrMask(uint64_t Val);
72
73 void Profile(FoldingSetNodeID &ID) const {
74 Profile(ID, Data, Vals);
75 }
76 static void Profile(FoldingSetNodeID &ID, Constant *Data,
77 ArrayRef Vals) {
78 ID.AddPointer(Data);
79 for (ArrayRef::iterator I = Vals.begin(), E = Vals.end();
80 I != E; ++I)
81 ID.AddPointer(*I);
82 }
83 };
84
85 //===----------------------------------------------------------------------===//
86 /// \class
87 /// \brief This class represents a set of attributes.
88 class AttributeSetImpl : public FoldingSetNode {
89 // AttributesSet is uniqued, these should not be publicly available.
90 void operator=(const AttributeSetImpl &) LLVM_DELETED_FUNCTION;
91 AttributeSetImpl(const AttributeSetImpl &) LLVM_DELETED_FUNCTION;
92 public:
93 LLVMContext &Context;
94 SmallVector Attrs;
95
96 AttributeSetImpl(LLVMContext &C, ArrayRef attrs)
97 : Context(C), Attrs(attrs.begin(), attrs.end()) {}
98
99 void Profile(FoldingSetNodeID &ID) const {
100 Profile(ID, Attrs);
101 }
102 static void Profile(FoldingSetNodeID &ID, ArrayRef Attrs){
103 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
104 ID.AddInteger(Attrs[i].Attrs.getBitMask());
105 ID.AddInteger(Attrs[i].Index);
106 }
107 }
108 };
109
110 } // end llvm namespace
111
112 #endif
0 //===-- Attribute.cpp - Implement AttributesList -------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Attribute, AttributeImpl, AttrBuilder,
10 // AttributeSetImpl, and AttributeSet classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Attributes.h"
15 #include "AttributeImpl.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Atomic.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/Mutex.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Type.h"
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 // Attribute Implementation
29 //===----------------------------------------------------------------------===//
30
31 Attribute Attribute::get(LLVMContext &Context, ArrayRef Vals) {
32 AttrBuilder B;
33 for (ArrayRef::iterator I = Vals.begin(), E = Vals.end();
34 I != E; ++I)
35 B.addAttribute(*I);
36 return Attribute::get(Context, B);
37 }
38
39 Attribute Attribute::get(LLVMContext &Context, AttrBuilder &B) {
40 // If there are no attributes, return an empty Attribute class.
41 if (!B.hasAttributes())
42 return Attribute();
43
44 // Otherwise, build a key to look up the existing attributes.
45 LLVMContextImpl *pImpl = Context.pImpl;
46 FoldingSetNodeID ID;
47 ID.AddInteger(B.getBitMask());
48
49 void *InsertPoint;
50 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
51
52 if (!PA) {
53 // If we didn't find any existing attributes of the same shape then create a
54 // new one and insert it.
55 PA = new AttributeImpl(Context, B.getBitMask());
56 pImpl->AttrsSet.InsertNode(PA, InsertPoint);
57 }
58
59 // Return the AttributesList that we found or created.
60 return Attribute(PA);
61 }
62
63 bool Attribute::hasAttribute(AttrKind Val) const {
64 return pImpl && pImpl->hasAttribute(Val);
65 }
66
67 bool Attribute::hasAttributes() const {
68 return pImpl && pImpl->hasAttributes();
69 }
70
71 bool Attribute::hasAttributes(const Attribute &A) const {
72 return pImpl && pImpl->hasAttributes(A);
73 }
74
75 /// This returns the alignment field of an attribute as a byte alignment value.
76 unsigned Attribute::getAlignment() const {
77 if (!hasAttribute(Attribute::Alignment))
78 return 0;
79 return 1U << ((pImpl->getAlignment() >> 16) - 1);
80 }
81
82 /// This returns the stack alignment field of an attribute as a byte alignment
83 /// value.
84 unsigned Attribute::getStackAlignment() const {
85 if (!hasAttribute(Attribute::StackAlignment))
86 return 0;
87 return 1U << ((pImpl->getStackAlignment() >> 26) - 1);
88 }
89
90 bool Attribute::operator==(AttrKind K) const {
91 return pImpl && pImpl->contains(K);
92 }
93
94 bool Attribute::operator!=(AttrKind K) const {
95 return !(pImpl && pImpl->contains(K));
96 }
97
98 uint64_t Attribute::getBitMask() const {
99 return pImpl ? pImpl->getBitMask() : 0;
100 }
101
102 Attribute Attribute::typeIncompatible(Type *Ty) {
103 AttrBuilder Incompatible;
104
105 if (!Ty->isIntegerTy())
106 // Attribute that only apply to integers.
107 Incompatible.addAttribute(Attribute::SExt)
108 .addAttribute(Attribute::ZExt);
109
110 if (!Ty->isPointerTy())
111 // Attribute that only apply to pointers.
112 Incompatible.addAttribute(Attribute::ByVal)
113 .addAttribute(Attribute::Nest)
114 .addAttribute(Attribute::NoAlias)
115 .addAttribute(Attribute::NoCapture)
116 .addAttribute(Attribute::StructRet);
117
118 return Attribute::get(Ty->getContext(), Incompatible);
119 }
120
121 /// encodeLLVMAttributesForBitcode - This returns an integer containing an
122 /// encoding of all the LLVM attributes found in the given attribute bitset.
123 /// Any change to this encoding is a breaking change to bitcode compatibility.
124 uint64_t Attribute::encodeLLVMAttributesForBitcode(Attribute Attrs) {
125 // FIXME: It doesn't make sense to store the alignment information as an
126 // expanded out value, we should store it as a log2 value. However, we can't
127 // just change that here without breaking bitcode compatibility. If this ever
128 // becomes a problem in practice, we should introduce new tag numbers in the
129 // bitcode file and have those tags use a more efficiently encoded alignment
130 // field.
131
132 // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
133 // log2 encoded value. Shift the bits above the alignment up by 11 bits.
134 uint64_t EncodedAttrs = Attrs.getBitMask() & 0xffff;
135 if (Attrs.hasAttribute(Attribute::Alignment))
136 EncodedAttrs |= Attrs.getAlignment() << 16;
137 EncodedAttrs |= (Attrs.getBitMask() & (0xffffULL << 21)) << 11;
138 return EncodedAttrs;
139 }
140
141 /// decodeLLVMAttributesForBitcode - This returns an attribute bitset containing
142 /// the LLVM attributes that have been decoded from the given integer. This
143 /// function must stay in sync with 'encodeLLVMAttributesForBitcode'.
144 Attribute Attribute::decodeLLVMAttributesForBitcode(LLVMContext &C,
145 uint64_t EncodedAttrs) {
146 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
147 // the bits above 31 down by 11 bits.
148 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
149 assert((!Alignment || isPowerOf2_32(Alignment)) &&
150 "Alignment must be a power of two.");
151
152 AttrBuilder B(EncodedAttrs & 0xffff);
153 if (Alignment)
154 B.addAlignmentAttr(Alignment);
155 B.addRawValue((EncodedAttrs & (0xffffULL << 32)) >> 11);
156 return Attribute::get(C, B);
157 }
158
159 std::string Attribute::getAsString() const {
160 std::string Result;
161 if (hasAttribute(Attribute::ZExt))
162 Result += "zeroext ";
163 if (hasAttribute(Attribute::SExt))
164 Result += "signext ";
165 if (hasAttribute(Attribute::NoReturn))
166 Result += "noreturn ";
167 if (hasAttribute(Attribute::NoUnwind))
168 Result += "nounwind ";
169 if (hasAttribute(Attribute::UWTable))
170 Result += "uwtable ";
171 if (hasAttribute(Attribute::ReturnsTwice))
172 Result += "returns_twice ";
173 if (hasAttribute(Attribute::InReg))
174 Result += "inreg ";
175 if (hasAttribute(Attribute::NoAlias))
176 Result += "noalias ";
177 if (hasAttribute(Attribute::NoCapture))
178 Result += "nocapture ";
179 if (hasAttribute(Attribute::StructRet))
180 Result += "sret ";
181 if (hasAttribute(Attribute::ByVal))
182 Result += "byval ";
183 if (hasAttribute(Attribute::Nest))
184 Result += "nest ";
185 if (hasAttribute(Attribute::ReadNone))
186 Result += "readnone ";
187 if (hasAttribute(Attribute::ReadOnly))
188 Result += "readonly ";
189 if (hasAttribute(Attribute::OptimizeForSize))
190 Result += "optsize ";
191 if (hasAttribute(Attribute::NoInline))
192 Result += "noinline ";
193 if (hasAttribute(Attribute::InlineHint))
194 Result += "inlinehint ";
195 if (hasAttribute(Attribute::AlwaysInline))
196 Result += "alwaysinline ";
197 if (hasAttribute(Attribute::StackProtect))
198 Result += "ssp ";
199 if (hasAttribute(Attribute::StackProtectReq))
200 Result += "sspreq ";
201 if (hasAttribute(Attribute::NoRedZone))
202 Result += "noredzone ";
203 if (hasAttribute(Attribute::NoImplicitFloat))
204 Result += "noimplicitfloat ";
205 if (hasAttribute(Attribute::Naked))
206 Result += "naked ";
207 if (hasAttribute(Attribute::NonLazyBind))
208 Result += "nonlazybind ";
209 if (hasAttribute(Attribute::AddressSafety))
210 Result += "address_safety ";
211 if (hasAttribute(Attribute::MinSize))
212 Result += "minsize ";
213 if (hasAttribute(Attribute::StackAlignment)) {
214 Result += "alignstack(";
215 Result += utostr(getStackAlignment());
216 Result += ") ";
217 }
218 if (hasAttribute(Attribute::Alignment)) {
219 Result += "align ";
220 Result += utostr(getAlignment());
221 Result += " ";
222 }
223 if (hasAttribute(Attribute::NoDuplicate))
224 Result += "noduplicate ";
225 // Trim the trailing space.
226 assert(!Result.empty() && "Unknown attribute!");
227 Result.erase(Result.end()-1);
228 return Result;
229 }
230
231 //===----------------------------------------------------------------------===//
232 // AttrBuilder Implementation
233 //===----------------------------------------------------------------------===//
234
235 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val){
236 Bits |= AttributeImpl::getAttrMask(Val);
237 return *this;
238 }
239
240 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
241 Bits |= Val;
242 return *this;
243 }
244
245 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
246 if (Align == 0) return *this;
247 assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
248 assert(Align <= 0x40000000 && "Alignment too large.");
249 Bits |= (Log2_32(Align) + 1) << 16;
250 return *this;
251 }
252 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align){
253 // Default alignment, allow the target to define how to align it.
254 if (Align == 0) return *this;
255 assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
256 assert(Align <= 0x100 && "Alignment too large.");
257 Bits |= (Log2_32(Align) + 1) << 26;
258 return *this;
259 }
260
261 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
262 Bits &= ~AttributeImpl::getAttrMask(Val);
263 return *this;
264 }
265
266 AttrBuilder &AttrBuilder::addAttributes(const Attribute &A) {
267 Bits |= A.getBitMask();
268 return *this;
269 }
270
271 AttrBuilder &AttrBuilder::removeAttributes(const Attribute &A){
272 Bits &= ~A.getBitMask();
273 return *this;
274 }
275
276 bool AttrBuilder::contains(Attribute::AttrKind A) const {
277 return Bits & AttributeImpl::getAttrMask(A);
278 }
279
280 bool AttrBuilder::hasAttributes() const {
281 return Bits != 0;
282 }
283 bool AttrBuilder::hasAttributes(const Attribute &A) const {
284 return Bits & A.getBitMask();
285 }
286 bool AttrBuilder::hasAlignmentAttr() const {
287 return Bits & AttributeImpl::getAttrMask(Attribute::Alignment);
288 }
289
290 uint64_t AttrBuilder::getAlignment() const {
291 if (!hasAlignmentAttr())
292 return 0;
293 return 1ULL <<
294 (((Bits & AttributeImpl::getAttrMask(Attribute::Alignment)) >> 16) - 1);
295 }
296
297 uint64_t AttrBuilder::getStackAlignment() const {
298 if (!hasAlignmentAttr())
299 return 0;
300 return 1ULL <<
301 (((Bits & AttributeImpl::getAttrMask(Attribute::StackAlignment))>>26)-1);
302 }
303
304 //===----------------------------------------------------------------------===//
305 // AttributeImpl Definition
306 //===----------------------------------------------------------------------===//
307
308 AttributeImpl::AttributeImpl(LLVMContext &C, uint64_t data) {
309 Data = ConstantInt::get(Type::getInt64Ty(C), data);
310 }
311 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data) {
312 Data = ConstantInt::get(Type::getInt64Ty(C), data);
313 }
314 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data,
315 ArrayRef values) {
316 Data = ConstantInt::get(Type::getInt64Ty(C), data);
317 Vals.reserve(values.size());
318 Vals.append(values.begin(), values.end());
319 }
320 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef data) {
321 Data = ConstantDataArray::getString(C, data);
322 }
323
324 bool AttributeImpl::contains(Attribute::AttrKind Kind) const {
325 if (ConstantInt *CI = dyn_cast(Data))
326 return CI->getZExtValue() == Kind;
327 return false;
328 }
329
330 bool AttributeImpl::contains(StringRef Kind) const {
331 if (ConstantDataArray *CDA = dyn_cast(Data))
332 if (CDA->isString())
333 return CDA->getAsString() == Kind;
334 return false;
335 }
336
337 uint64_t AttributeImpl::getBitMask() const {
338 // FIXME: Remove this.
339 return cast(Data)->getZExtValue();
340 }
341
342 uint64_t AttributeImpl::getAttrMask(uint64_t Val) {
343 switch (Val) {
344 case Attribute::None: return 0;
345 case Attribute::ZExt: return 1 << 0;
346 case Attribute::SExt: return 1 << 1;
347 case Attribute::NoReturn: return 1 << 2;
348 case Attribute::InReg: return 1 << 3;
349 case Attribute::StructRet: return 1 << 4;
350 case Attribute::NoUnwind: return 1 << 5;
351 case Attribute::NoAlias: return 1 << 6;
352 case Attribute::ByVal: return 1 << 7;
353 case Attribute::Nest: return 1 << 8;
354 case Attribute::ReadNone: return 1 << 9;
355 case Attribute::ReadOnly: return 1 << 10;
356 case Attribute::NoInline: return 1 << 11;
357 case Attribute::AlwaysInline: return 1 << 12;
358 case Attribute::OptimizeForSize: return 1 << 13;
359 case Attribute::StackProtect: return 1 << 14;
360 case Attribute::StackProtectReq: return 1 << 15;
361 case Attribute::Alignment: return 31 << 16;
362 case Attribute::NoCapture: return 1 << 21;
363 case Attribute::NoRedZone: return 1 << 22;
364 case Attribute::NoImplicitFloat: return 1 << 23;
365 case Attribute::Naked: return 1 << 24;
366 case Attribute::InlineHint: return 1 << 25;
367 case Attribute::StackAlignment: return 7 << 26;
368 case Attribute::ReturnsTwice: return 1 << 29;
369 case Attribute::UWTable: return 1 << 30;
370 case Attribute::NonLazyBind: return 1U << 31;
371 case Attribute::AddressSafety: return 1ULL << 32;
372 case Attribute::MinSize: return 1ULL << 33;
373 case Attribute::NoDuplicate: return 1ULL << 34;
374 }
375 llvm_unreachable("Unsupported attribute type");
376 }
377
378 bool AttributeImpl::hasAttribute(uint64_t A) const {
379 return (getBitMask() & getAttrMask(A)) != 0;
380 }
381
382 bool AttributeImpl::hasAttributes() const {
383 return getBitMask() != 0;
384 }
385
386 bool AttributeImpl::hasAttributes(const Attribute &A) const {
387 // FIXME: getBitMask() won't work here in the future.
388 return getBitMask() & A.getBitMask();
389 }
390
391 uint64_t AttributeImpl::getAlignment() const {
392 return getBitMask() & getAttrMask(Attribute::Alignment);
393 }
394
395 uint64_t AttributeImpl::getStackAlignment() const {
396 return getBitMask() & getAttrMask(Attribute::StackAlignment);
397 }
398
399 //===----------------------------------------------------------------------===//
400 // AttributeSetImpl Definition
401 //===----------------------------------------------------------------------===//
402
403 AttributeSet AttributeSet::get(LLVMContext &C,
404 ArrayRef Attrs) {
405 // If there are no attributes then return a null AttributesList pointer.
406 if (Attrs.empty())
407 return AttributeSet();
408
409 #ifndef NDEBUG
410 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
411 assert(Attrs[i].Attrs.hasAttributes() &&
412 "Pointless attribute!");
413 assert((!i || Attrs[i-1].Index < Attrs[i].Index) &&
414 "Misordered AttributesList!");
415 }
416 #endif
417
418 // Otherwise, build a key to look up the existing attributes.
419 LLVMContextImpl *pImpl = C.pImpl;
420 FoldingSetNodeID ID;
421 AttributeSetImpl::Profile(ID, Attrs);
422
423 void *InsertPoint;
424 AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID,
425 InsertPoint);
426
427 // If we didn't find any existing attributes of the same shape then
428 // create a new one and insert it.
429 if (!PA) {
430 PA = new AttributeSetImpl(C, Attrs);
431 pImpl->AttrsLists.InsertNode(PA, InsertPoint);
432 }
433
434 // Return the AttributesList that we found or created.
435 return AttributeSet(PA);
436 }
437
438 //===----------------------------------------------------------------------===//
439 // AttributeSet Method Implementations
440 //===----------------------------------------------------------------------===//
441
442 const AttributeSet &AttributeSet::operator=(const AttributeSet &RHS) {
443 AttrList = RHS.AttrList;
444 return *this;
445 }
446
447 /// getNumSlots - Return the number of slots used in this attribute list.
448 /// This is the number of arguments that have an attribute set on them
449 /// (including the function itself).
450 unsigned AttributeSet::getNumSlots() const {
451 return AttrList ? AttrList->Attrs.size() : 0;
452 }
453
454 /// getSlot - Return the AttributeWithIndex at the specified slot. This
455 /// holds a number plus a set of attributes.
456 const AttributeWithIndex &AttributeSet::getSlot(unsigned Slot) const {
457 assert(AttrList && Slot < AttrList->Attrs.size() && "Slot # out of range!");
458 return AttrList->Attrs[Slot];
459 }
460
461 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
462 return getAttributes(Index).hasAttribute(Kind);
463 }
464
465 bool AttributeSet::hasAttributes(unsigned Index) const {
466 return getAttributes(Index).hasAttributes();
467 }
468
469 std::string AttributeSet::getAsString(unsigned Index) const {
470 return getAttributes(Index).getAsString();
471 }
472
473 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
474 return getAttributes(Index).getStackAlignment();
475 }
476
477 uint64_t AttributeSet::getBitMask(unsigned Index) const {
478 // FIXME: Remove this.
479 return getAttributes(Index).getBitMask();
480 }
481
482 /// getAttributes - The attributes for the specified index are returned.
483 /// Attributes for the result are denoted with Idx = 0. Function attributes are
484 /// denoted with Idx = ~0.
485 Attribute AttributeSet::getAttributes(unsigned Idx) const {
486 if (AttrList == 0) return Attribute();
487
488 const SmallVectorImpl &Attrs = AttrList->Attrs;
489 for (unsigned i = 0, e = Attrs.size(); i != e && Attrs[i].Index <= Idx; ++i)
490 if (Attrs[i].Index == Idx)
491 return Attrs[i].Attrs;
492
493 return Attribute();
494 }
495
496 /// hasAttrSomewhere - Return true if the specified attribute is set for at
497 /// least one parameter or for the return value.
498 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
499 if (AttrList == 0) return false;
500
501 const SmallVector &Attrs = AttrList->Attrs;
502 for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
503 if (Attrs[i].Attrs.hasAttribute(Attr))
504 return true;
505
506 return false;
507 }
508
509 AttributeSet AttributeSet::addAttr(LLVMContext &C, unsigned Idx,
510 Attribute Attrs) const {
511 Attribute OldAttrs = getAttributes(Idx);
512 #ifndef NDEBUG
513 // FIXME it is not obvious how this should work for alignment.
514 // For now, say we can't change a known alignment.
515 unsigned OldAlign = OldAttrs.getAlignment();
516 unsigned NewAlign = Attrs.getAlignment();
517 assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
518 "Attempt to change alignment!");
519 #endif
520
521 AttrBuilder NewAttrs =
522 AttrBuilder(OldAttrs).addAttributes(Attrs);
523 if (NewAttrs == AttrBuilder(OldAttrs))
524 return *this;
525
526 SmallVector NewAttrList;
527 if (AttrList == 0)
528 NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
529 else {
530 const SmallVector &OldAttrList = AttrList->Attrs;
531 unsigned i = 0, e = OldAttrList.size();
532 // Copy attributes for arguments before this one.
533 for (; i != e && OldAttrList[i].Index < Idx; ++i)
534 NewAttrList.push_back(OldAttrList[i]);
535
536 // If there are attributes already at this index, merge them in.
537 if (i != e && OldAttrList[i].Index == Idx) {
538 Attrs =
539 Attribute::get(C, AttrBuilder(Attrs).
540 addAttributes(OldAttrList[i].Attrs));
541 ++i;
542 }
543
544 NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
545
546 // Copy attributes for arguments after this one.
547 NewAttrList.insert(NewAttrList.end(),
548 OldAttrList.begin()+i, OldAttrList.end());
549 }
550
551 return get(C, NewAttrList);
552 }
553
554 AttributeSet AttributeSet::removeAttr(LLVMContext &C, unsigned Idx,
555 Attribute Attrs) const {
556 #ifndef NDEBUG
557 // FIXME it is not obvious how this should work for alignment.
558 // For now, say we can't pass in alignment, which no current use does.
559 assert(!Attrs.hasAttribute(Attribute::Alignment) &&
560 "Attempt to exclude alignment!");
561 #endif
562 if (AttrList == 0) return AttributeSet();
563
564 Attribute OldAttrs = getAttributes(Idx);
565 AttrBuilder NewAttrs =
566 AttrBuilder(OldAttrs).removeAttributes(Attrs);
567 if (NewAttrs == AttrBuilder(OldAttrs))
568 return *this;
569
570 SmallVector NewAttrList;
571 const SmallVector &OldAttrList = AttrList->Attrs;
572 unsigned i = 0, e = OldAttrList.size();
573
574 // Copy attributes for arguments before this one.
575 for (; i != e && OldAttrList[i].Index < Idx; ++i)
576 NewAttrList.push_back(OldAttrList[i]);
577
578 // If there are attributes already at this index, merge them in.
579 assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
580 Attrs = Attribute::get(C, AttrBuilder(OldAttrList[i].Attrs).
581 removeAttributes(Attrs));
582 ++i;
583 if (Attrs.hasAttributes()) // If any attributes left for this param, add them.
584 NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
585
586 // Copy attributes for arguments after this one.
587 NewAttrList.insert(NewAttrList.end(),
588 OldAttrList.begin()+i, OldAttrList.end());
589
590 return get(C, NewAttrList);
591 }
592
593 void AttributeSet::dump() const {
594 dbgs() << "PAL[ ";
595 for (unsigned i = 0; i < getNumSlots(); ++i) {
596 const AttributeWithIndex &PAWI = getSlot(i);
597 dbgs() << "{" << PAWI.Index << "," << PAWI.Attrs.getAsString() << "} ";
598 }
599
600 dbgs() << "]\n";
601 }
0 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the auto-upgrade helper functions
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/AutoUpgrade.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Function.h"
16 #include "llvm/IRBuilder.h"
17 #include "llvm/Instruction.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Module.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include
25 using namespace llvm;
26
27 // Upgrade the declarations of the SSE4.1 functions whose arguments have
28 // changed their type from v4f32 to v2i64.
29 static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID,
30 Function *&NewFn) {
31 // Check whether this is an old version of the function, which received
32 // v4f32 arguments.
33 Type *Arg0Type = F->getFunctionType()->getParamType(0);
34 if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
35 return false;
36
37 // Yes, it's old, replace it with new version.
38 F->setName(F->getName() + ".old");
39 NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
40 return true;
41 }
42
43 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
44 assert(F && "Illegal to upgrade a non-existent Function.");
45
46 // Quickly eliminate it, if it's not a candidate.
47 StringRef Name = F->getName();
48 if (Name.size() <= 8 || !Name.startswith("llvm."))
49 return false;
50 Name = Name.substr(5); // Strip off "llvm."
51
52 switch (Name[0]) {
53 default: break;
54 case 'a': {
55 if (Name.startswith("arm.neon.vclz")) {
56 Type* args[2] = {
57 F->arg_begin()->getType(),
58 Type::getInt1Ty(F->getContext())
59 };
60 // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
61 // the end of the name. Change name from llvm.arm.neon.vclz.* to
62 // llvm.ctlz.*
63 FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
64 NewFn = Function::Create(fType, F->getLinkage(),
65 "llvm.ctlz." + Name.substr(14), F->getParent());
66 return true;
67 }
68 if (Name.startswith("arm.neon.vcnt")) {
69 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
70 F->arg_begin()->getType());
71 return true;
72 }
73 break;
74 }
75 case 'c': {
76 if (Name.startswith("ctlz.") && F->arg_size() == 1) {
77 F->setName(Name + ".old");
78 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
79 F->arg_begin()->getType());
80 return true;
81 }
82 if (Name.startswith("cttz.") && F->arg_size() == 1) {
83 F->setName(Name + ".old");
84 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
85 F->arg_begin()->getType());
86 return true;
87 }
88 break;
89 }
90 case 'x': {
91 if (Name.startswith("x86.sse2.pcmpeq.") ||
92 Name.startswith("x86.sse2.pcmpgt.") ||
93 Name.startswith("x86.avx2.pcmpeq.") ||
94 Name.startswith("x86.avx2.pcmpgt.") ||
95 Name.startswith("x86.avx.vpermil.") ||
96 Name == "x86.avx.movnt.dq.256" ||
97 Name == "x86.avx.movnt.pd.256" ||
98 Name == "x86.avx.movnt.ps.256" ||
99 (Name.startswith("x86.xop.vpcom") && F->arg_size() == 2)) {
100 NewFn = 0;
101 return true;
102 }
103 // SSE4.1 ptest functions may have an old signature.
104 if (Name.startswith("x86.sse41.ptest")) {
105 if (Name == "x86.sse41.ptestc")
106 return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn);
107 if (Name == "x86.sse41.ptestz")
108 return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn);
109 if (Name == "x86.sse41.ptestnzc")
110 return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
111 }
112 // frcz.ss/sd may need to have an argument dropped
113 if (Name.startswith("x86.xop.vfrcz.ss") && F->arg_size() == 2) {
114 F->setName(Name + ".old");
115 NewFn = Intrinsic::getDeclaration(F->getParent(),
116 Intrinsic::x86_xop_vfrcz_ss);
117 return true;
118 }
119 if (Name.startswith("x86.xop.vfrcz.sd") && F->arg_size() == 2) {
120 F->setName(Name + ".old");
121 NewFn = Intrinsic::getDeclaration(F->getParent(),
122 Intrinsic::x86_xop_vfrcz_sd);
123 return true;
124 }
125 // Fix the FMA4 intrinsics to remove the 4
126 if (Name.startswith("x86.fma4.")) {
127 F->setName("llvm.x86.fma" + Name.substr(8));
128 NewFn = F;
129 return true;
130 }
131 break;
132 }
133 }
134
135 // This may not belong here. This function is effectively being overloaded
136 // to both detect an intrinsic which needs upgrading, and to provide the
137 // upgraded form of the intrinsic. We should perhaps have two separate
138 // functions for this.
139 return false;
140 }
141
142 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
143 NewFn = 0;
144 bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
145
146 // Upgrade intrinsic attributes. This does not change the function.
147 if (NewFn)
148 F = NewFn;
149 if (unsigned id = F->getIntrinsicID())
150 F->setAttributes(Intrinsic::getAttributes(F->getContext(),
151 (Intrinsic::ID)id));
152 return Upgraded;
153 }
154
155 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
156 // Nothing to do yet.
157 return false;
158 }
159
160 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
161 // upgraded intrinsic. All argument and return casting must be provided in
162 // order to seamlessly integrate with existing context.
163 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
164 Function *F = CI->getCalledFunction();
165 LLVMContext &C = CI->getContext();
166 IRBuilder<> Builder(C);
167 Builder.SetInsertPoint(CI->getParent(), CI);
168
169 assert(F && "Intrinsic call is not direct?");
170
171 if (!NewFn) {
172 // Get the Function's name.
173 StringRef Name = F->getName();
174
175 Value *Rep;
176 // Upgrade packed integer vector compares intrinsics to compare instructions
177 if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
178 Name.startswith("llvm.x86.avx2.pcmpeq.")) {
179 Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
180 "pcmpeq");
181 // need to sign extend since icmp returns vector of i1
182 Rep = Builder.CreateSExt(Rep, CI->getType(), "");
183 } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
184 Name.startswith("llvm.x86.avx2.pcmpgt.")) {
185 Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
186 "pcmpgt");
187 // need to sign extend since icmp returns vector of i1
188 Rep = Builder.CreateSExt(Rep, CI->getType(), "");
189 } else if (Name == "llvm.x86.avx.movnt.dq.256" ||
190 Name == "llvm.x86.avx.movnt.ps.256" ||
191 Name == "llvm.x86.avx.movnt.pd.256") {
192 IRBuilder<> Builder(C);
193 Builder.SetInsertPoint(CI->getParent(), CI);
194
195 Module *M = F->getParent();
196 SmallVector Elts;
197 Elts.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
198 MDNode *Node = MDNode::get(C, Elts);
199
200 Value *Arg0 = CI->getArgOperand(0);
201 Value *Arg1 = CI->getArgOperand(1);
202
203 // Convert the type of the pointer to a pointer to the stored type.
204 Value *BC = Builder.CreateBitCast(Arg0,
205 PointerType::getUnqual(Arg1->getType()),
206 "cast");
207 StoreInst *SI = Builder.CreateStore(Arg1, BC);
208 SI->setMetadata(M->getMDKindID("nontemporal"), Node);
209 SI->setAlignment(16);
210
211 // Remove intrinsic.
212 CI->eraseFromParent();
213 return;
214 } else if (Name.startswith("llvm.x86.xop.vpcom")) {
215 Intrinsic::ID intID;
216 if (Name.endswith("ub"))
217 intID = Intrinsic::x86_xop_vpcomub;
218 else if (Name.endswith("uw"))
219 intID = Intrinsic::x86_xop_vpcomuw;
220 else if (Name.endswith("ud"))
221 intID = Intrinsic::x86_xop_vpcomud;
222 else if (Name.endswith("uq"))
223 intID = Intrinsic::x86_xop_vpcomuq;
224 else if (Name.endswith("b"))
225 intID = Intrinsic::x86_xop_vpcomb;
226 else if (Name.endswith("w"))
227 intID = Intrinsic::x86_xop_vpcomw;
228 else if (Name.endswith("d"))
229 intID = Intrinsic::x86_xop_vpcomd;
230 else if (Name.endswith("q"))
231 intID = Intrinsic::x86_xop_vpcomq;
232 else
233 llvm_unreachable("Unknown suffix");
234
235 Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom"
236 unsigned Imm;
237 if (Name.startswith("lt"))
238 Imm = 0;
239 else if (Name.startswith("le"))
240 Imm = 1;
241 else if (Name.startswith("gt"))
242 Imm = 2;
243 else if (Name.startswith("ge"))
244 Imm = 3;
245 else if (Name.startswith("eq"))
246 Imm = 4;
247 else if (Name.startswith("ne"))
248 Imm = 5;
249 else if (Name.startswith("true"))
250 Imm = 6;
251 else if (Name.startswith("false"))
252 Imm = 7;
253 else
254 llvm_unreachable("Unknown condition");
255
256 Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
257 Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0),
258 CI->getArgOperand(1), Builder.getInt8(Imm));
259 } else {
260 bool PD128 = false, PD256 = false, PS128 = false, PS256 = false;
261 if (Name == "llvm.x86.avx.vpermil.pd.256")
262 PD256 = true;
263 else if (Name == "llvm.x86.avx.vpermil.pd")
264 PD128 = true;
265 else if (Name == "llvm.x86.avx.vpermil.ps.256")
266 PS256 = true;
267 else if (Name == "llvm.x86.avx.vpermil.ps")
268 PS128 = true;
269
270 if (PD256 || PD128 || PS256 || PS128) {
271 Value *Op0 = CI->getArgOperand(0);
272 unsigned Imm = cast(CI->getArgOperand(1))->getZExtValue();
273 SmallVector Idxs;
274
275 if (PD128)
276 for (unsigned i = 0; i != 2; ++i)
277 Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1));
278 else if (PD256)
279 for (unsigned l = 0; l != 4; l+=2)
280 for (unsigned i = 0; i != 2; ++i)
281 Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l));
282 else if (PS128)
283 for (unsigned i = 0; i != 4; ++i)
284 Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3));
285 else if (PS256)
286 for (unsigned l = 0; l != 8; l+=4)
287 for (unsigned i = 0; i != 4; ++i)
288 Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l));
289 else
290 llvm_unreachable("Unexpected function");
291
292 Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs));
293 } else {
294 llvm_unreachable("Unknown function for CallInst upgrade.");
295 }
296 }
297
298 CI->replaceAllUsesWith(Rep);
299 CI->eraseFromParent();
300 return;
301 }
302
303 std::string Name = CI->getName().str();
304 CI->setName(Name + ".old");
305
306 switch (NewFn->getIntrinsicID()) {
307 default:
308 llvm_unreachable("Unknown function for CallInst upgrade.");
309
310 case Intrinsic::ctlz:
311 case Intrinsic::cttz:
312 assert(CI->getNumArgOperands() == 1 &&
313 "Mismatch between function args and call args");
314 CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
315 Builder.getFalse(), Name));
316 CI->eraseFromParent();
317 return;
318
319 case Intrinsic::arm_neon_vclz: {
320 // Change name from llvm.arm.neon.vclz.* to llvm.ctlz.*
321 CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
322 Builder.getFalse(),
323 "llvm.ctlz." + Name.substr(14)));
324 CI->eraseFromParent();
325 return;
326 }
327 case Intrinsic::ctpop: {
328 CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0)));
329 CI->eraseFromParent();
330 return;
331 }
332
333 case Intrinsic::x86_xop_vfrcz_ss:
334 case Intrinsic::x86_xop_vfrcz_sd:
335 CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1),
336 Name));
337 CI->eraseFromParent();
338 return;
339
340 case Intrinsic::x86_sse41_ptestc:
341 case Intrinsic::x86_sse41_ptestz:
342 case Intrinsic::x86_sse41_ptestnzc: {
343 // The arguments for these intrinsics used to be v4f32, and changed
344 // to v2i64. This is purely a nop, since those are bitwise intrinsics.
345 // So, the only thing required is a bitcast for both arguments.
346 // First, check the arguments have the old type.
347 Value *Arg0 = CI->getArgOperand(0);
348 if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
349 return;
350
351 // Old intrinsic, add bitcasts
352 Value *Arg1 = CI->getArgOperand(1);
353
354 Value *BC0 =
355 Builder.CreateBitCast(Arg0,
356 VectorType::get(Type::getInt64Ty(C), 2),
357 "cast");
358 Value *BC1 =
359 Builder.CreateBitCast(Arg1,
360 VectorType::get(Type::getInt64Ty(C), 2),
361 "cast");
362
363 CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name);
364 CI->replaceAllUsesWith(NewCall);
365 CI->eraseFromParent();
366 return;
367 }
368 }
369 }
370
371 // This tests each Function to determine if it needs upgrading. When we find
372 // one we are interested in, we then upgrade all calls to reflect the new
373 // function.
374 void llvm::UpgradeCallsToIntrinsic(Function* F) {
375 assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
376
377 // Upgrade the function and check if it is a totaly new function.
378 Function *NewFn;
379 if (UpgradeIntrinsicFunction(F, NewFn)) {
380 if (NewFn != F) {
381 // Replace all uses to the old function with the new one if necessary.
382 for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
383 UI != UE; ) {
384 if (CallInst *CI = dyn_cast(*UI++))
385 UpgradeIntrinsicCall(CI, NewFn);
386 }
387 // Remove old function, no longer used, from the module.
388 F->eraseFromParent();
389 }
390 }
391 }
392
0 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the BasicBlock class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/BasicBlock.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Support/CFG.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "llvm/Type.h"
23 #include
24 using namespace llvm;
25
26 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
27 if (Function *F = getParent())
28 return &F->getValueSymbolTable();
29 return 0;
30 }
31
32 LLVMContext &BasicBlock::getContext() const {
33 return getType()->getContext();
34 }
35
36 // Explicit instantiation of SymbolTableListTraits since some of the methods
37 // are not in the public header file...
38 template class llvm::SymbolTableListTraits;
39
40
41 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42 BasicBlock *InsertBefore)
43 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0) {
44
45 // Make sure that we get added to a function
46 LeakDetector::addGarbageObject(this);
47
48 if (InsertBefore) {
49 assert(NewParent &&
50 "Cannot insert block before another block with no function!");
51 NewParent->getBasicBlockList().insert(InsertBefore, this);
52 } else if (NewParent) {
53 NewParent->getBasicBlockList().push_back(this);
54 }
55
56 setName(Name);
57 }
58
59
60 BasicBlock::~BasicBlock() {
61 // If the address of the block is taken and it is being deleted (e.g. because
62 // it is dead), this means that there is either a dangling constant expr
63 // hanging off the block, or an undefined use of the block (source code
64 // expecting the address of a label to keep the block alive even though there
65 // is no indirect branch). Handle these cases by zapping the BlockAddress
66 // nodes. There are no other possible uses at this point.
67 if (hasAddressTaken()) {
68 assert(!use_empty() && "There should be at least one blockaddress!");
69 Constant *Replacement =
70 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
71 while (!use_empty()) {
72 BlockAddress *BA = cast(use_back());
73 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
74 BA->getType()));
75 BA->destroyConstant();
76 }
77 }
78
79 assert(getParent() == 0 && "BasicBlock still linked into the program!");
80 dropAllReferences();
81 InstList.clear();
82 }
83
84 void BasicBlock::setParent(Function *parent) {
85 if (getParent())
86 LeakDetector::addGarbageObject(this);
87
88 // Set Parent=parent, updating instruction symtab entries as appropriate.
89 InstList.setSymTabObject(&Parent, parent);
90
91 if (getParent())
92 LeakDetector::removeGarbageObject(this);
93 }
94
95 void BasicBlock::removeFromParent() {
96 getParent()->getBasicBlockList().remove(this);
97 }
98
99 void BasicBlock::eraseFromParent() {
100 getParent()->getBasicBlockList().erase(this);
101 }
102
103 /// moveBefore - Unlink this basic block from its current function and
104 /// insert it into the function that MovePos lives in, right before MovePos.
105 void BasicBlock::moveBefore(BasicBlock *MovePos) {
106 MovePos->getParent()->getBasicBlockList().splice(MovePos,
107 getParent()->getBasicBlockList(), this);
108 }
109
110 /// moveAfter - Unlink this basic block from its current function and
111 /// insert it into the function that MovePos lives in, right after MovePos.
112 void BasicBlock::moveAfter(BasicBlock *MovePos) {
113 Function::iterator I = MovePos;
114 MovePos->getParent()->getBasicBlockList().splice(++I,
115 getParent()->getBasicBlockList(), this);
116 }
117
118
119 TerminatorInst *BasicBlock::getTerminator() {
120 if (InstList.empty()) return 0;
121 return dyn_cast(&InstList.back());
122 }
123
124 const TerminatorInst *BasicBlock::getTerminator() const {
125 if (InstList.empty()) return 0;
126 return dyn_cast(&InstList.back());
127 }
128
129 Instruction* BasicBlock::getFirstNonPHI() {
130 BasicBlock::iterator i = begin();
131 // All valid basic blocks should have a terminator,
132 // which is not a PHINode. If we have an invalid basic
133 // block we'll get an assertion failure when dereferencing
134 // a past-the-end iterator.
135 while (isa(i)) ++i;
136 return &*i;
137 }
138
139 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
140 BasicBlock::iterator i = begin();
141 // All valid basic blocks should have a terminator,
142 // which is not a PHINode. If we have an invalid basic
143 // block we'll get an assertion failure when dereferencing
144 // a past-the-end iterator.
145 while (isa(i) || isa(i)) ++i;
146 return &*i;
147 }
148
149 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
150 // All valid basic blocks should have a terminator,
151 // which is not a PHINode. If we have an invalid basic
152 // block we'll get an assertion failure when dereferencing
153 // a past-the-end iterator.
154 BasicBlock::iterator i = begin();
155 for (;; ++i) {
156 if (isa(i) || isa(i))
157 continue;
158
159 const IntrinsicInst *II = dyn_cast(i);
160 if (!II)
161 break;
162 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
163 II->getIntrinsicID() != Intrinsic::lifetime_end)
164 break;
165 }
166 return &*i;
167 }
168
169 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
170 iterator InsertPt = getFirstNonPHI();
171 if (isa(InsertPt)) ++InsertPt;
172 return InsertPt;
173 }
174
175 void BasicBlock::dropAllReferences() {
176 for(iterator I = begin(), E = end(); I != E; ++I)
177 I->dropAllReferences();
178 }
179
180 /// getSinglePredecessor - If this basic block has a single predecessor block,
181 /// return the block, otherwise return a null pointer.
182 BasicBlock *BasicBlock::getSinglePredecessor() {
183