Remove one of the odious 'Raw' methods.
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attributes.cpp - Implement AttributesList -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // \file
11 // \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeSetImpl, and AttributeSet classes.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/Support/Atomic.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Attribute Construction Methods
31 //===----------------------------------------------------------------------===//
32
33 Attribute Attribute::get(LLVMContext &Context, Constant *Kind, Constant *Val) {
34   LLVMContextImpl *pImpl = Context.pImpl;
35   FoldingSetNodeID ID;
36   ID.AddPointer(Kind);
37   if (Val) ID.AddPointer(Val);
38
39   void *InsertPoint;
40   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
41
42   if (!PA) {
43     // If we didn't find any existing attributes of the same shape then create a
44     // new one and insert it.
45     PA = (!Val) ?
46       new AttributeImpl(Context, Kind) :
47       new AttributeImpl(Context, Kind, Val);
48     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
49   }
50
51   // Return the AttributesList that we found or created.
52   return Attribute(PA);
53 }
54
55 Attribute Attribute::get(LLVMContext &Context, AttrKind Kind, Constant *Val) {
56   ConstantInt *KindVal = ConstantInt::get(Type::getInt64Ty(Context), Kind);
57   return get(Context, KindVal, Val);
58 }
59
60 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
61   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
62   assert(Align <= 0x40000000 && "Alignment too large.");
63   return get(Context, Alignment,
64              ConstantInt::get(Type::getInt64Ty(Context), Align));
65 }
66
67 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
68                                            uint64_t Align) {
69   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
70   assert(Align <= 0x100 && "Alignment too large.");
71   return get(Context, StackAlignment,
72              ConstantInt::get(Type::getInt64Ty(Context), Align));
73 }
74
75 //===----------------------------------------------------------------------===//
76 // Attribute Accessor Methods
77 //===----------------------------------------------------------------------===//
78
79 bool Attribute::hasAttribute(AttrKind Val) const {
80   return pImpl && pImpl->hasAttribute(Val);
81 }
82
83 Constant *Attribute::getAttributeKind() const {
84   return pImpl ? pImpl->getAttributeKind() : 0;
85 }
86
87 ArrayRef<Constant*> Attribute::getAttributeValues() const {
88   return pImpl ? pImpl->getAttributeValues() : ArrayRef<Constant*>();
89 }
90
91 /// This returns the alignment field of an attribute as a byte alignment value.
92 unsigned Attribute::getAlignment() const {
93   if (!hasAttribute(Attribute::Alignment))
94     return 0;
95   return pImpl->getAlignment();
96 }
97
98 /// This returns the stack alignment field of an attribute as a byte alignment
99 /// value.
100 unsigned Attribute::getStackAlignment() const {
101   if (!hasAttribute(Attribute::StackAlignment))
102     return 0;
103   return pImpl->getStackAlignment();
104 }
105
106 std::string Attribute::getAsString() const {
107   if (!pImpl) return "";
108
109   if (hasAttribute(Attribute::AddressSafety))
110     return "address_safety";
111   if (hasAttribute(Attribute::AlwaysInline))
112     return "alwaysinline";
113   if (hasAttribute(Attribute::ByVal))
114     return "byval";
115   if (hasAttribute(Attribute::InlineHint))
116     return "inlinehint";
117   if (hasAttribute(Attribute::InReg))
118     return "inreg";
119   if (hasAttribute(Attribute::MinSize))
120     return "minsize";
121   if (hasAttribute(Attribute::Naked))
122     return "naked";
123   if (hasAttribute(Attribute::Nest))
124     return "nest";
125   if (hasAttribute(Attribute::NoAlias))
126     return "noalias";
127   if (hasAttribute(Attribute::NoCapture))
128     return "nocapture";
129   if (hasAttribute(Attribute::NoDuplicate))
130     return "noduplicate";
131   if (hasAttribute(Attribute::NoImplicitFloat))
132     return "noimplicitfloat";
133   if (hasAttribute(Attribute::NoInline))
134     return "noinline";
135   if (hasAttribute(Attribute::NonLazyBind))
136     return "nonlazybind";
137   if (hasAttribute(Attribute::NoRedZone))
138     return "noredzone";
139   if (hasAttribute(Attribute::NoReturn))
140     return "noreturn";
141   if (hasAttribute(Attribute::NoUnwind))
142     return "nounwind";
143   if (hasAttribute(Attribute::OptimizeForSize))
144     return "optsize";
145   if (hasAttribute(Attribute::ReadNone))
146     return "readnone";
147   if (hasAttribute(Attribute::ReadOnly))
148     return "readonly";
149   if (hasAttribute(Attribute::ReturnsTwice))
150     return "returns_twice";
151   if (hasAttribute(Attribute::SExt))
152     return "signext";
153   if (hasAttribute(Attribute::StackProtect))
154     return "ssp";
155   if (hasAttribute(Attribute::StackProtectReq))
156     return "sspreq";
157   if (hasAttribute(Attribute::StackProtectStrong))
158     return "sspstrong";
159   if (hasAttribute(Attribute::StructRet))
160     return "sret";
161   if (hasAttribute(Attribute::UWTable))
162     return "uwtable";
163   if (hasAttribute(Attribute::ZExt))
164     return "zeroext";
165
166   // FIXME: These should be output like this:
167   //
168   //   align=4
169   //   alignstack=8
170   //
171   if (hasAttribute(Attribute::StackAlignment)) {
172     std::string Result;
173     Result += "alignstack(";
174     Result += utostr(getStackAlignment());
175     Result += ")";
176     return Result;
177   }
178   if (hasAttribute(Attribute::Alignment)) {
179     std::string Result;
180     Result += "align ";
181     Result += utostr(getAlignment());
182     return Result;
183   }
184
185   // Convert target-dependent attributes to strings of the form:
186   //
187   //   "kind"
188   //   "kind" = "value"
189   //   "kind" = ("value1" "value2" "value3" )
190   //
191   if (ConstantDataArray *CDA =
192       dyn_cast<ConstantDataArray>(pImpl->getAttributeKind())) {
193     std::string Result;
194     Result += '\"' + CDA->getAsString().str() + '"';
195
196     ArrayRef<Constant*> Vals = pImpl->getAttributeValues();
197     if (Vals.empty()) return Result;
198     Result += " = ";
199     if (Vals.size() > 1) Result += '(';
200     for (ArrayRef<Constant*>::iterator I = Vals.begin(), E = Vals.end();
201          I != E; ) {
202       ConstantDataArray *CDA = cast<ConstantDataArray>(*I++);
203       Result += '\"' + CDA->getAsString().str() + '"';
204       if (I != E) Result += ' ';
205     }
206     if (Vals.size() > 1) Result += ')';
207   }
208
209   llvm_unreachable("Unknown attribute");
210 }
211
212 bool Attribute::operator==(AttrKind K) const {
213   return (pImpl && *pImpl == K) || (!pImpl && K == None);
214 }
215 bool Attribute::operator!=(AttrKind K) const {
216   return !(*this == K);
217 }
218
219 bool Attribute::operator<(Attribute A) const {
220   if (!pImpl && !A.pImpl) return false;
221   if (!pImpl) return true;
222   if (!A.pImpl) return false;
223   return *pImpl < *A.pImpl;
224 }
225
226 //===----------------------------------------------------------------------===//
227 // AttributeImpl Definition
228 //===----------------------------------------------------------------------===//
229
230 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind kind)
231   : Context(C) {
232   Kind = ConstantInt::get(Type::getInt64Ty(C), kind);
233 }
234 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind kind,
235                              ArrayRef<Constant*> values)
236   : Context(C) {
237   Kind = ConstantInt::get(Type::getInt64Ty(C), kind);
238   Vals.reserve(values.size());
239   Vals.append(values.begin(), values.end());
240 }
241 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef kind)
242   : Context(C) {
243   Kind = ConstantDataArray::getString(C, kind);
244 }
245
246 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
247   if (ConstantInt *CI = dyn_cast<ConstantInt>(Kind))
248     return CI->getZExtValue() == A;
249   return false;
250 }
251
252 uint64_t AttributeImpl::getAlignment() const {
253   assert(hasAttribute(Attribute::Alignment) &&
254          "Trying to retrieve the alignment from a non-alignment attr!");
255   return cast<ConstantInt>(Vals[0])->getZExtValue();
256 }
257
258 uint64_t AttributeImpl::getStackAlignment() const {
259   assert(hasAttribute(Attribute::StackAlignment) &&
260          "Trying to retrieve the stack alignment from a non-alignment attr!");
261   return cast<ConstantInt>(Vals[0])->getZExtValue();
262 }
263
264 bool AttributeImpl::operator==(Attribute::AttrKind kind) const {
265   if (ConstantInt *CI = dyn_cast<ConstantInt>(Kind))
266     return CI->getZExtValue() == kind;
267   return false;
268 }
269 bool AttributeImpl::operator!=(Attribute::AttrKind kind) const {
270   return !(*this == kind);
271 }
272
273 bool AttributeImpl::operator==(StringRef kind) const {
274   if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Kind))
275     if (CDA->isString())
276       return CDA->getAsString() == kind;
277   return false;
278 }
279
280 bool AttributeImpl::operator!=(StringRef kind) const {
281   return !(*this == kind);
282 }
283
284 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
285   if (!Kind && !AI.Kind) return false;
286   if (!Kind && AI.Kind) return true;
287   if (Kind && !AI.Kind) return false;
288
289   ConstantInt *ThisCI = dyn_cast<ConstantInt>(Kind);
290   ConstantInt *ThatCI = dyn_cast<ConstantInt>(AI.Kind);
291
292   ConstantDataArray *ThisCDA = dyn_cast<ConstantDataArray>(Kind);
293   ConstantDataArray *ThatCDA = dyn_cast<ConstantDataArray>(AI.Kind);
294
295   if (ThisCI && ThatCI)
296     return ThisCI->getZExtValue() < ThatCI->getZExtValue();
297
298   if (ThisCI && ThatCDA)
299     return true;
300
301   if (ThisCDA && ThatCI)
302     return false;
303
304   return ThisCDA->getAsString() < ThatCDA->getAsString();
305 }
306
307 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
308   // FIXME: Remove this.
309   switch (Val) {
310   case Attribute::EndAttrKinds:
311   case Attribute::AttrKindEmptyKey:
312   case Attribute::AttrKindTombstoneKey:
313     llvm_unreachable("Synthetic enumerators which should never get here");
314
315   case Attribute::None:            return 0;
316   case Attribute::ZExt:            return 1 << 0;
317   case Attribute::SExt:            return 1 << 1;
318   case Attribute::NoReturn:        return 1 << 2;
319   case Attribute::InReg:           return 1 << 3;
320   case Attribute::StructRet:       return 1 << 4;
321   case Attribute::NoUnwind:        return 1 << 5;
322   case Attribute::NoAlias:         return 1 << 6;
323   case Attribute::ByVal:           return 1 << 7;
324   case Attribute::Nest:            return 1 << 8;
325   case Attribute::ReadNone:        return 1 << 9;
326   case Attribute::ReadOnly:        return 1 << 10;
327   case Attribute::NoInline:        return 1 << 11;
328   case Attribute::AlwaysInline:    return 1 << 12;
329   case Attribute::OptimizeForSize: return 1 << 13;
330   case Attribute::StackProtect:    return 1 << 14;
331   case Attribute::StackProtectReq: return 1 << 15;
332   case Attribute::Alignment:       return 31 << 16;
333   case Attribute::NoCapture:       return 1 << 21;
334   case Attribute::NoRedZone:       return 1 << 22;
335   case Attribute::NoImplicitFloat: return 1 << 23;
336   case Attribute::Naked:           return 1 << 24;
337   case Attribute::InlineHint:      return 1 << 25;
338   case Attribute::StackAlignment:  return 7 << 26;
339   case Attribute::ReturnsTwice:    return 1 << 29;
340   case Attribute::UWTable:         return 1 << 30;
341   case Attribute::NonLazyBind:     return 1U << 31;
342   case Attribute::AddressSafety:   return 1ULL << 32;
343   case Attribute::MinSize:         return 1ULL << 33;
344   case Attribute::NoDuplicate:     return 1ULL << 34;
345   case Attribute::StackProtectStrong: return 1ULL << 35;
346   }
347   llvm_unreachable("Unsupported attribute type");
348 }
349
350 //===----------------------------------------------------------------------===//
351 // AttributeSetNode Definition
352 //===----------------------------------------------------------------------===//
353
354 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
355                                         ArrayRef<Attribute> Attrs) {
356   if (Attrs.empty())
357     return 0;
358
359   // Otherwise, build a key to look up the existing attributes.
360   LLVMContextImpl *pImpl = C.pImpl;
361   FoldingSetNodeID ID;
362
363   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
364   std::sort(SortedAttrs.begin(), SortedAttrs.end());
365
366   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
367          E = SortedAttrs.end(); I != E; ++I)
368     I->Profile(ID);
369
370   void *InsertPoint;
371   AttributeSetNode *PA =
372     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
373
374   // If we didn't find any existing attributes of the same shape then create a
375   // new one and insert it.
376   if (!PA) {
377     PA = new AttributeSetNode(SortedAttrs);
378     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
379   }
380
381   // Return the AttributesListNode that we found or created.
382   return PA;
383 }
384
385 bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
386   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
387          E = AttrList.end(); I != E; ++I)
388     if (I->hasAttribute(Kind))
389       return true;
390   return false;
391 }
392
393 unsigned AttributeSetNode::getAlignment() const {
394   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
395          E = AttrList.end(); I != E; ++I)
396     if (I->hasAttribute(Attribute::Alignment))
397       return I->getAlignment();
398   return 0;
399 }
400
401 unsigned AttributeSetNode::getStackAlignment() const {
402   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
403          E = AttrList.end(); I != E; ++I)
404     if (I->hasAttribute(Attribute::StackAlignment))
405       return I->getStackAlignment();
406   return 0;
407 }
408
409 std::string AttributeSetNode::getAsString() const {
410   std::string Str = "";
411   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
412          E = AttrList.end(); I != E; ++I) {
413     if (I != AttrList.begin()) Str += " ";
414     Str += I->getAsString();
415   }
416   return Str;
417 }
418
419 //===----------------------------------------------------------------------===//
420 // AttributeSetImpl Definition
421 //===----------------------------------------------------------------------===//
422
423 uint64_t AttributeSetImpl::Raw(uint64_t Index) const {
424   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
425     if (getSlotIndex(I) != Index) continue;
426     const AttributeSetNode *ASN = AttrNodes[I].second;
427     AttrBuilder B;
428
429     for (AttributeSetNode::const_iterator II = ASN->begin(),
430            IE = ASN->end(); II != IE; ++II)
431       B.addAttribute(*II);
432     return B.Raw();
433   }
434
435   return 0;
436 }
437
438 //===----------------------------------------------------------------------===//
439 // AttributeSet Construction and Mutation Methods
440 //===----------------------------------------------------------------------===//
441
442 AttributeSet
443 AttributeSet::getImpl(LLVMContext &C,
444                       ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
445   LLVMContextImpl *pImpl = C.pImpl;
446   FoldingSetNodeID ID;
447   AttributeSetImpl::Profile(ID, Attrs);
448
449   void *InsertPoint;
450   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
451
452   // If we didn't find any existing attributes of the same shape then
453   // create a new one and insert it.
454   if (!PA) {
455     PA = new AttributeSetImpl(C, Attrs);
456     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
457   }
458
459   // Return the AttributesList that we found or created.
460   return AttributeSet(PA);
461 }
462
463 AttributeSet AttributeSet::get(LLVMContext &C,
464                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
465   // If there are no attributes then return a null AttributesList pointer.
466   if (Attrs.empty())
467     return AttributeSet();
468
469 #ifndef NDEBUG
470   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
471     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
472            "Misordered Attributes list!");
473     assert(Attrs[i].second != Attribute::None &&
474            "Pointless attribute!");
475   }
476 #endif
477
478   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
479   // list.
480   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
481   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
482          E = Attrs.end(); I != E; ) {
483     unsigned Index = I->first;
484     SmallVector<Attribute, 4> AttrVec;
485     while (I != E && I->first == Index) {
486       AttrVec.push_back(I->second);
487       ++I;
488     }
489
490     AttrPairVec.push_back(std::make_pair(Index,
491                                          AttributeSetNode::get(C, AttrVec)));
492   }
493
494   return getImpl(C, AttrPairVec);
495 }
496
497 AttributeSet AttributeSet::get(LLVMContext &C,
498                                ArrayRef<std::pair<unsigned,
499                                                   AttributeSetNode*> > Attrs) {
500   // If there are no attributes then return a null AttributesList pointer.
501   if (Attrs.empty())
502     return AttributeSet();
503
504   return getImpl(C, Attrs);
505 }
506
507 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
508   if (!B.hasAttributes())
509     return AttributeSet();
510
511   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
512   for (AttrBuilder::iterator I = B.begin(), E = B.end(); I != E; ++I) {
513     Attribute::AttrKind Kind = *I;
514     if (Kind == Attribute::Alignment)
515       Attrs.push_back(std::make_pair(Idx, Attribute::
516                                      getWithAlignment(C, B.getAlignment())));
517     else if (Kind == Attribute::StackAlignment)
518       Attrs.push_back(std::make_pair(Idx, Attribute::
519                               getWithStackAlignment(C, B.getStackAlignment())));
520     else
521       Attrs.push_back(std::make_pair(Idx, Attribute::get(C, Kind)));
522   }
523
524   return get(C, Attrs);
525 }
526
527 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
528                                ArrayRef<Attribute::AttrKind> Kind) {
529   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
530   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
531          E = Kind.end(); I != E; ++I)
532     Attrs.push_back(std::make_pair(Idx, Attribute::get(C, *I)));
533   return get(C, Attrs);
534 }
535
536 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
537   if (Attrs.empty()) return AttributeSet();
538
539   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
540   for (unsigned I = 0, E = Attrs.size(); I != E; ++I) {
541     AttributeSet AS = Attrs[I];
542     if (!AS.pImpl) continue;
543     AttrNodeVec.append(AS.pImpl->AttrNodes.begin(), AS.pImpl->AttrNodes.end());
544   }
545
546   return getImpl(C, AttrNodeVec);
547 }
548
549 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
550                                         Attribute::AttrKind Attr) const {
551   return addAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
552 }
553
554 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
555                                          AttributeSet Attrs) const {
556   if (!pImpl) return Attrs;
557   if (!Attrs.pImpl) return *this;
558
559 #ifndef NDEBUG
560   // FIXME it is not obvious how this should work for alignment. For now, say
561   // we can't change a known alignment.
562   unsigned OldAlign = getParamAlignment(Idx);
563   unsigned NewAlign = Attrs.getParamAlignment(Idx);
564   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
565          "Attempt to change alignment!");
566 #endif
567
568   // Add the attribute slots before the one we're trying to add.
569   SmallVector<AttributeSet, 4> AttrSet;
570   uint64_t NumAttrs = pImpl->getNumAttributes();
571   AttributeSet AS;
572   uint64_t LastIndex = 0;
573   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
574     if (getSlotIndex(I) >= Idx) {
575       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
576       break;
577     }
578     LastIndex = I + 1;
579     AttrSet.push_back(getSlotAttributes(I));
580   }
581
582   // Now add the attribute into the correct slot. There may already be an
583   // AttributeSet there.
584   AttrBuilder B(AS, Idx);
585
586   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
587     if (Attrs.getSlotIndex(I) == Idx) {
588       for (AttributeSetImpl::const_iterator II = Attrs.pImpl->begin(I),
589              IE = Attrs.pImpl->end(I); II != IE; ++II)
590         B.addAttribute(*II);
591       break;
592     }
593
594   AttrSet.push_back(AttributeSet::get(C, Idx, B));
595
596   // Add the remaining attribute slots.
597   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
598     AttrSet.push_back(getSlotAttributes(I));
599
600   return get(C, AttrSet);
601 }
602
603 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
604                                            Attribute::AttrKind Attr) const {
605   return removeAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
606 }
607
608 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
609                                             AttributeSet Attrs) const {
610   if (!pImpl) return AttributeSet();
611   if (!Attrs.pImpl) return *this;
612
613 #ifndef NDEBUG
614   // FIXME it is not obvious how this should work for alignment.
615   // For now, say we can't pass in alignment, which no current use does.
616   assert(!Attrs.hasAttribute(Idx, Attribute::Alignment) &&
617          "Attempt to change alignment!");
618 #endif
619
620   // Add the attribute slots before the one we're trying to add.
621   SmallVector<AttributeSet, 4> AttrSet;
622   uint64_t NumAttrs = pImpl->getNumAttributes();
623   AttributeSet AS;
624   uint64_t LastIndex = 0;
625   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
626     if (getSlotIndex(I) >= Idx) {
627       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
628       break;
629     }
630     LastIndex = I + 1;
631     AttrSet.push_back(getSlotAttributes(I));
632   }
633
634   // Now remove the attribute from the correct slot. There may already be an
635   // AttributeSet there.
636   AttrBuilder B(AS, Idx);
637
638   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
639     if (Attrs.getSlotIndex(I) == Idx) {
640       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Idx);
641       break;
642     }
643
644   AttrSet.push_back(AttributeSet::get(C, Idx, B));
645
646   // Add the remaining attribute slots.
647   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
648     AttrSet.push_back(getSlotAttributes(I));
649
650   return get(C, AttrSet);
651 }
652
653 //===----------------------------------------------------------------------===//
654 // AttributeSet Accessor Methods
655 //===----------------------------------------------------------------------===//
656
657 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
658   return pImpl && hasAttributes(Idx) ?
659     AttributeSet::get(pImpl->getContext(),
660                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
661                         std::make_pair(Idx, getAttributes(Idx)))) :
662     AttributeSet();
663 }
664
665 AttributeSet AttributeSet::getRetAttributes() const {
666   return pImpl && hasAttributes(ReturnIndex) ?
667     AttributeSet::get(pImpl->getContext(),
668                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
669                         std::make_pair(ReturnIndex,
670                                        getAttributes(ReturnIndex)))) :
671     AttributeSet();
672 }
673
674 AttributeSet AttributeSet::getFnAttributes() const {
675   return pImpl && hasAttributes(FunctionIndex) ?
676     AttributeSet::get(pImpl->getContext(),
677                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
678                         std::make_pair(FunctionIndex,
679                                        getAttributes(FunctionIndex)))) :
680     AttributeSet();
681 }
682
683 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
684   AttributeSetNode *ASN = getAttributes(Index);
685   return ASN ? ASN->hasAttribute(Kind) : false;
686 }
687
688 bool AttributeSet::hasAttributes(unsigned Index) const {
689   AttributeSetNode *ASN = getAttributes(Index);
690   return ASN ? ASN->hasAttributes() : false;
691 }
692
693 /// \brief Return true if the specified attribute is set for at least one
694 /// parameter or for the return value.
695 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
696   if (pImpl == 0) return false;
697
698   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
699     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
700            IE = pImpl->end(I); II != IE; ++II)
701       if (II->hasAttribute(Attr))
702         return true;
703
704   return false;
705 }
706
707 unsigned AttributeSet::getParamAlignment(unsigned Index) const {
708   AttributeSetNode *ASN = getAttributes(Index);
709   return ASN ? ASN->getAlignment() : 0;
710 }
711
712 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
713   AttributeSetNode *ASN = getAttributes(Index);
714   return ASN ? ASN->getStackAlignment() : 0;
715 }
716
717 std::string AttributeSet::getAsString(unsigned Index) const {
718   AttributeSetNode *ASN = getAttributes(Index);
719   return ASN ? ASN->getAsString() : std::string("");
720 }
721
722 /// \brief The attributes for the specified index are returned.
723 AttributeSetNode *AttributeSet::getAttributes(unsigned Idx) const {
724   if (!pImpl) return 0;
725
726   // Loop through to find the attribute node we want.
727   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
728     if (pImpl->getSlotIndex(I) == Idx)
729       return pImpl->getSlotNode(I);
730
731   return 0;
732 }
733
734 AttributeSet::iterator AttributeSet::begin(unsigned Idx) const {
735   if (!pImpl)
736     return ArrayRef<Attribute>().begin();
737   return pImpl->begin(Idx);
738 }
739
740 AttributeSet::iterator AttributeSet::end(unsigned Idx) const {
741   if (!pImpl)
742     return ArrayRef<Attribute>().end();
743   return pImpl->end(Idx);
744 }
745
746 //===----------------------------------------------------------------------===//
747 // AttributeSet Introspection Methods
748 //===----------------------------------------------------------------------===//
749
750 /// \brief Return the number of slots used in this attribute list.  This is the
751 /// number of arguments that have an attribute set on them (including the
752 /// function itself).
753 unsigned AttributeSet::getNumSlots() const {
754   return pImpl ? pImpl->getNumAttributes() : 0;
755 }
756
757 uint64_t AttributeSet::getSlotIndex(unsigned Slot) const {
758   assert(pImpl && Slot < pImpl->getNumAttributes() &&
759          "Slot # out of range!");
760   return pImpl->getSlotIndex(Slot);
761 }
762
763 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
764   assert(pImpl && Slot < pImpl->getNumAttributes() &&
765          "Slot # out of range!");
766   return pImpl->getSlotAttributes(Slot);
767 }
768
769 uint64_t AttributeSet::Raw(unsigned Index) const {
770   // FIXME: Remove this.
771   return pImpl ? pImpl->Raw(Index) : 0;
772 }
773
774 void AttributeSet::dump() const {
775   dbgs() << "PAL[\n";
776
777   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
778     uint64_t Index = getSlotIndex(i);
779     dbgs() << "  { ";
780     if (Index == ~0U)
781       dbgs() << "~0U";
782     else
783       dbgs() << Index;
784     dbgs() << " => " << getAsString(Index) << " }\n";
785   }
786
787   dbgs() << "]\n";
788 }
789
790 //===----------------------------------------------------------------------===//
791 // AttrBuilder Method Implementations
792 //===----------------------------------------------------------------------===//
793
794 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Idx)
795   : Alignment(0), StackAlignment(0) {
796   AttributeSetImpl *pImpl = AS.pImpl;
797   if (!pImpl) return;
798
799   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
800     if (pImpl->getSlotIndex(I) != Idx) continue;
801
802     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
803            IE = pImpl->end(I); II != IE; ++II)
804       addAttribute(*II);
805
806     break;
807   }
808 }
809
810 void AttrBuilder::clear() {
811   Attrs.clear();
812   Alignment = StackAlignment = 0;
813 }
814
815 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
816   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
817          "Adding alignment attribute without adding alignment value!");
818   Attrs.insert(Val);
819   return *this;
820 }
821
822 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
823   ConstantInt *Kind = cast<ConstantInt>(Attr.getAttributeKind());
824   Attribute::AttrKind KindVal = Attribute::AttrKind(Kind->getZExtValue());
825   Attrs.insert(KindVal);
826
827   if (KindVal == Attribute::Alignment)
828     Alignment = Attr.getAlignment();
829   else if (KindVal == Attribute::StackAlignment)
830     StackAlignment = Attr.getStackAlignment();
831   return *this;
832 }
833
834 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
835   Attrs.erase(Val);
836
837   if (Val == Attribute::Alignment)
838     Alignment = 0;
839   else if (Val == Attribute::StackAlignment)
840     StackAlignment = 0;
841
842   return *this;
843 }
844
845 AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
846   unsigned Idx = ~0U;
847   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
848     if (A.getSlotIndex(I) == Index) {
849       Idx = I;
850       break;
851     }
852
853   assert(Idx != ~0U && "Couldn't find index in AttributeSet!");
854
855   for (AttributeSet::iterator I = A.begin(Idx), E = A.end(Idx); I != E; ++I) {
856     ConstantInt *CI = cast<ConstantInt>(I->getAttributeKind());
857     Attribute::AttrKind Kind = Attribute::AttrKind(CI->getZExtValue());
858     Attrs.erase(Kind);
859
860     if (Kind == Attribute::Alignment)
861       Alignment = 0;
862     else if (Kind == Attribute::StackAlignment)
863       StackAlignment = 0;
864   }
865
866   return *this;
867 }
868
869 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
870   if (Align == 0) return *this;
871
872   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
873   assert(Align <= 0x40000000 && "Alignment too large.");
874
875   Attrs.insert(Attribute::Alignment);
876   Alignment = Align;
877   return *this;
878 }
879
880 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
881   // Default alignment, allow the target to define how to align it.
882   if (Align == 0) return *this;
883
884   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
885   assert(Align <= 0x100 && "Alignment too large.");
886
887   Attrs.insert(Attribute::StackAlignment);
888   StackAlignment = Align;
889   return *this;
890 }
891
892 bool AttrBuilder::contains(Attribute::AttrKind A) const {
893   return Attrs.count(A);
894 }
895
896 bool AttrBuilder::hasAttributes() const {
897   return !Attrs.empty();
898 }
899
900 bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
901   return Raw() & A.Raw(Index);
902 }
903
904 bool AttrBuilder::hasAlignmentAttr() const {
905   return Alignment != 0;
906 }
907
908 bool AttrBuilder::operator==(const AttrBuilder &B) {
909   SmallVector<Attribute::AttrKind, 8> This(Attrs.begin(), Attrs.end());
910   SmallVector<Attribute::AttrKind, 8> That(B.Attrs.begin(), B.Attrs.end());
911   return This == That;
912 }
913
914 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
915   if (!Val) return *this;
916
917   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
918        I = Attribute::AttrKind(I + 1)) {
919     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
920       Attrs.insert(I);
921  
922       if (I == Attribute::Alignment)
923         Alignment = 1ULL << ((A >> 16) - 1);
924       else if (I == Attribute::StackAlignment)
925         StackAlignment = 1ULL << ((A >> 26)-1);
926     }
927   }
928  
929   return *this;
930 }
931
932 uint64_t AttrBuilder::Raw() const {
933   uint64_t Mask = 0;
934
935   for (DenseSet<Attribute::AttrKind>::const_iterator I = Attrs.begin(),
936          E = Attrs.end(); I != E; ++I) {
937     Attribute::AttrKind Kind = *I;
938
939     if (Kind == Attribute::Alignment)
940       Mask |= (Log2_32(Alignment) + 1) << 16;
941     else if (Kind == Attribute::StackAlignment)
942       Mask |= (Log2_32(StackAlignment) + 1) << 26;
943     else
944       Mask |= AttributeImpl::getAttrMask(Kind);
945   }
946
947   return Mask;
948 }
949
950 //===----------------------------------------------------------------------===//
951 // AttributeFuncs Function Defintions
952 //===----------------------------------------------------------------------===//
953
954 AttributeSet AttributeFuncs::typeIncompatible(Type *Ty, uint64_t Index) {
955   AttrBuilder Incompatible;
956
957   if (!Ty->isIntegerTy())
958     // Attribute that only apply to integers.
959     Incompatible.addAttribute(Attribute::SExt)
960       .addAttribute(Attribute::ZExt);
961
962   if (!Ty->isPointerTy())
963     // Attribute that only apply to pointers.
964     Incompatible.addAttribute(Attribute::ByVal)
965       .addAttribute(Attribute::Nest)
966       .addAttribute(Attribute::NoAlias)
967       .addAttribute(Attribute::NoCapture)
968       .addAttribute(Attribute::StructRet);
969
970   return AttributeSet::get(Ty->getContext(), Index, Incompatible);
971 }
972
973 /// \brief This returns an integer containing an encoding of all the LLVM
974 /// attributes found in the given attribute bitset.  Any change to this encoding
975 /// is a breaking change to bitcode compatibility.
976 /// N.B. This should be used only by the bitcode reader!
977 uint64_t AttributeFuncs::encodeLLVMAttributesForBitcode(AttributeSet Attrs,
978                                                         unsigned Index) {
979   // FIXME: It doesn't make sense to store the alignment information as an
980   // expanded out value, we should store it as a log2 value.  However, we can't
981   // just change that here without breaking bitcode compatibility.  If this ever
982   // becomes a problem in practice, we should introduce new tag numbers in the
983   // bitcode file and have those tags use a more efficiently encoded alignment
984   // field.
985
986   // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
987   // log2 encoded value. Shift the bits above the alignment up by 11 bits.
988   uint64_t EncodedAttrs = Attrs.Raw(Index) & 0xffff;
989   if (Attrs.hasAttribute(Index, Attribute::Alignment))
990     EncodedAttrs |= Attrs.getParamAlignment(Index) << 16;
991   EncodedAttrs |= (Attrs.Raw(Index) & (0xffffULL << 21)) << 11;
992   return EncodedAttrs;
993 }
994
995 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
996 /// been decoded from the given integer. This function must stay in sync with
997 /// 'encodeLLVMAttributesForBitcode'.
998 /// N.B. This should be used only by the bitcode reader!
999 void AttributeFuncs::decodeLLVMAttributesForBitcode(LLVMContext &C,
1000                                                     AttrBuilder &B,
1001                                                     uint64_t EncodedAttrs) {
1002   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1003   // the bits above 31 down by 11 bits.
1004   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1005   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1006          "Alignment must be a power of two.");
1007
1008   if (Alignment)
1009     B.addAlignmentAttr(Alignment);
1010   B.addRawValue(((EncodedAttrs & (0xffffULL << 32)) >> 11) |
1011                 (EncodedAttrs & 0xffff));
1012 }